注解的存在主要是为了简化XML的配置。Spring6倡导全注解开发。
我们来回顾一下:
注解使用@interface定义,注解中的属性与接口的方法的定义一样。
自定义一个注解Component
@Target(ElementType.TYPE_USE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Component {
String value();
//String name();
//int[] ages();
}
该注解上面修饰的注解包括:Target注解和Retention注解,这两个注解被称为元注解。
@Target注解用来修饰注解可以出现的位置。只有一个属性,是一个value,且类型是一个枚举类型。
具体值:
@Retention用来标注注解最终保留位置,同样只有一个属性,是一个value,且类型是一个枚举类型。
具体值:
使用注解的语法:
使用某个注解的时候,属性名是value,value可以省略
如果属性值是一个数组,并且值只有一个,那么{}可以省略
//@Component(value = "userBean")
@Component("userBean")
public class User {
}
步骤:
public class ReflectAnnotationTest1 {
public static void main(String[] args) throws Exception {
//1.获取类
Class<?> aClass = Class.forName("com.review.bean.User");
//2.判断类上面有没有这个注解
if (aClass.isAnnotationPresent(Component.class)) {
//3.有则获取类上的注解
Component annotation = aClass.getAnnotation(Component.class);
//4.访问注解属性
System.out.println(annotation.value());
}
}
}

还是使用之前的自定义注解Component和User类,再添加两个类,一个有Component注解,一个没有

Order类
@Component("orderBean")
public class Order {
}
Products类:
public class Products {
}
原理程序:
public class ReflectAnnotationTest2 {
public static void main(String[] args) {
Map<String ,Object> map = new HashMap<>();
//1.包名字
String packageName = "com.review.bean";
//2.扫描程序
//把'.'替换成'/',正则表达式中'.'代表任意,我们需要把普通的点替换,需要加个\,在java语言中两个斜杠代表一个斜杠。
String packagePath = packageName.replaceAll("\\.", "/");//变成 com/review/bean
//packagePath是一个在类根路径的路径,需要通过系统类加载器加载,自动返回一个URL路径
URL url = ClassLoader.getSystemClassLoader().getResource(packagePath);
String path = url.getPath();//获取绝对路径
//获取绝对路径下所有文件
File file = new File(path);
File[] files = file.listFiles();
//通过流编程遍历files
Arrays.stream(files).forEach(fileclass -> {
try {
//获取绝对路径类
String className = packageName + "." + fileclass.getName().split("\\.")[0];
//3.通过反射机制解析注解
Class<?> aClass = Class.forName(className);
if (aClass.isAnnotationPresent(Component.class)) {
Component annotation = aClass.getAnnotation(Component.class);
String beanId = annotation.value();
Object beanObj = aClass.newInstance();
//4.放到一个Map集合当中
map.put(beanId,beanObj);
}
} catch (Exception e) {
e.printStackTrace();
}
});
System.out.println(map);
}
}

负责声明Bean的注解,常见的包括四个:
源码如下:
@Component:
@Target(value = {ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface Component {
String value();
}
@Controller:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {
@AliasFor(
annotation = Component.class
)
String value() default "";
}
@Service注解:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {
@AliasFor(
annotation = Component.class
)
String value() default "";
}
@Repository:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {
@AliasFor(
annotation = Component.class
)
String value() default "";
}
通过源码可以看到,@Controller、@Service、@Repository这三个注解都是@Component注解的别名。
也就是说:这四个注解的功能都一样。用哪个都可以。
只是为了增强程序的可读性,建议:
如果把value属性彻底去掉,spring会自动取名,并且默认名字的规律是:Bean类名首字母小写即可。
如何使用以上的注解呢?
在Maven项目中,当加入spring-context依赖之后,会关联加入aop的依赖。所以这一步不用做。如果不是Maven项目,则需要把jar包导进库。
spring.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
</beans>
spring.xml添加指定要扫描的包:
<context:component-scan base-package="com.annotation.bean"/>
如果是多个包怎么办?有两种解决方案:
四个注解都用一下,在bean包下创建四个类
@Controller注解使用:创建User类
//@Controller 不写value的话,默认是user,就是类名首字母小写
@Controller(value = "user")
public class User {
}
@Service注解使用:创建Student类
@Service("studentBean")
public class Student {
}
@Repository使用:创建Order类
@Repository("orderBean")
public class Order {
}
@Component使用:创建Car类
@Component("carBean")
public class Car {
}
测试程序:
@Test
public void testBean(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
//User userBean = applicationContext.getBean("userBean", User.class);
User userBean = applicationContext.getBean("user", User.class);
System.out.println(userBean);
Car carBean = applicationContext.getBean("carBean", Car.class);
System.out.println(carBean);
Student studentBean = applicationContext.getBean("studentBean", Student.class);
System.out.println(studentBean);
Order orderBean = applicationContext.getBean("orderBean", Order.class);
System.out.println(orderBean);
}

假设在某个包下有很多Bean,有的Bean上标注了Component,有的标注了Controller,有的标注了Service,有的标注了Repository,
现在由于某种特殊业务的需要,只允许其中所有的Controller参与Bean管理,其他的都不实例化。这应该怎么办呢?
需要在配置文件的context:component-scan标签加一个属性use-default-filters,默认是true
use-default-filters="true"表示:使用spring默认的规则,只要有Component、Controller、Service、Repository中的任意一个注解标注,则进行实例化。
如果是默认值或者true,想让其特定注解失效,则添加context:exclude-filter标签
use-default-filters="false"表示:不再spring默认实例化规则,即使有Component、Controller、Service、Repository这些注解标注,也不再实例化。
如果设置成false后,想让其生效需要添加一个context:include-filter标签使特定的注解生效
type属性:需要生效的类型
expression:需要生效的全限定路径
这两种方式类似于黑名单和白名单
注意:因为Component注解是其他三个注解的”老大“,所以
创建bean2包,创建几个类,提供无参构造方法打印测试,为了方便测试,我们写在一个类里面:
@Component
public class A {
public A() {
System.out.println("A的无参数构造方法执行。。。");
}
}
@Controller
class B{
public B() {
System.out.println("B的无参数构造方法执行。。。");
}
}
@Service
class C{
public C() {
System.out.println("C的无参数构造方法执行。。。");
}
}
@Repository
class D{
public D() {
System.out.println("D的无参数构造方法执行。。。");
}
}
@Controller
class E{
public E() {
System.out.println("E的无参数构造方法执行。。。");
}
}
创建spring-choose.xml配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
</beans>
让其@Controller失效,spring-choose.xml配置:
<context:component-scan base-package="com.annotation.bean2">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
测试程序:因为只需要测试是否实例化,不用获取Bean
@Test
public void testBeanChoose(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-choose.xml");
}
运行发现A、C、D实例化

如果把失效注解换成@Component:
<context:component-scan base-package="com.annotation.bean2">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Component"/>
</context:component-scan>
再次运行测试程序:全都不生效了

记得上面的配置要注释掉,让其@Controller失效,spring-choose.xml配置:
<context:component-scan base-package="com.annotation.bean2" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
测试程序是同一个,再次运行:B、E实例化

如果把生效注解换成@Component:
<context:component-scan base-package="com.annotation.bean2" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Component"/>
</context:component-scan>
再次运行测试程序:全都生效

@Component @Controller @Service @Repository 这四个注解是用来声明Bean的,声明后这些Bean将被实例化。如何给Bean的属性赋值。给Bean属性赋值需要用到这些注解:
@Value注解的源码
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Value {
String value();
}
只负责简单类型的注入,属性名value,用来赋值,可以声明在属性上或setter方法上或构造方法的参数上,声明在属性上可以不提供setter方法。
创建bean3包
创建spring-value.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.annotation.bean3"/>
</beans>
在bean3包创建User1类:声明在属性上,先提供setter方法。
@Component
public class User1 {
@Value("张三")
private String name;
@Value("30")
private int age;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
测试程序:
@Test
public void testByValue(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-value.xml");
User1 user1 = applicationContext.getBean("user1", User1.class);
System.out.println(user1);
}

删掉setter方法,再次运行测试程序:发现声明在属性上可以不提供setter方法。

在bean3包,创建User2类:
@Component
public class User2 {
private String name;
private int age;
@Override
public String toString() {
return "User2{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Value("李四")
public void setName(String name) {
this.name = name;
}
@Value("20")
public void setAge(int age) {
this.age = age;
}
}
在上面测试程序添加:
User2 user2 = applicationContext.getBean("user2", User2.class);
System.out.println(user2);

在bean3包下,创建User3类
@Component
public class User3 {
private String name;
private int age;
@Override
public String toString() {
return "User3{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public User3(@Value("王五")String name, @Value("25")int age) {
this.name = name;
this.age = age;
}
}
在上面测试程序添加:
User3 user3 = applicationContext.getBean("user3", User3.class);
System.out.println(user3);

@Autowired 与 @Qualifier:Autowired翻译为:自动连线/自动装配,可以用来注入非简单类型
创建bean4包
创建spring-autowired.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.annotation.bean4"/>
</beans>
在bean4包下创建dao包,在dao包下创建一个OrderDao接口:
public interface OrderDao {
void insert();
}
在dao包下创建impl包,提供一个实现类:
@Repository
public class OrderDaoImplForMysql implements OrderDao {
@Override
public void insert() {
System.out.println("Mysql正在保存订单信息");
}
}
创建service包
@Autowired注解源码:
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
boolean required() default true;
}
@Autowired注解可以出现在:属性上、构造方法上、构造方法的参数上、setter方法上。同样注解如果声明在属性上可以不提供setter方法。当带参数的构造方法只有一个,@Autowired注解可以省略。
该注解有一个required属性,默认值是true,表示在注入的时候要求被注入的Bean必须是存在的,如果不存在则报错。如果required属性设置为false,表示注入的Bean存在或者不存在都没关系,存在的话就注入,不存在的话,也不报错。
在service创建一个OrderService类:先提供setter方法
@Service
public class OrderService {
@Autowired
private OrderDao orderDao;
public void setOrderDao(OrderDao orderDao) {
this.orderDao = orderDao;
}
public void generate(){
orderDao.insert();
}
}
测试程序:
@Test
public void testByAutowired(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-autowired.xml");
OrderService orderService = applicationContext.getBean("orderService", OrderService.class);
orderService.generate();
}

删掉setter方法,再次运行测试程序:发现声明在属性上可以不提供setter方法。

修改OrderService类:
@Service
public class OrderService {
/*@Autowired*/
private OrderDao orderDao;
@Autowired
public OrderService(OrderDao orderDao) {
this.orderDao = orderDao;
}
public void generate(){
orderDao.insert();
}
}
与上面相同的测试程序,再次运行:

@Service
public class OrderService {
/*@Autowired*/
private OrderDao orderDao;
/*@Autowired*/
public OrderService(@Autowired OrderDao orderDao) {
this.orderDao = orderDao;
}
public void generate(){
orderDao.insert();
}
}
再次运行测试程序:

当带参数的构造方法只有一个,@Autowired注解可以省略。
去掉@Autowired注解,再次运行程序:

如果加一个带参数的构造方法
@Service
public class OrderService {
/*@Autowired*/
private OrderDao orderDao;
/*@Autowired*/
public OrderService(OrderDao orderDao) {
this.orderDao = orderDao;
}
public OrderService(OrderDao orderDao,String s) {
this.orderDao = orderDao;
}
public void generate(){
orderDao.insert();
}
}
再次运行:报错,当带参数的构造方法只能有一个,有无参构造也不行,这个可以自己测试。

@Service
public class OrderService {
/*@Autowired*/
private OrderDao orderDao;
/*@Autowired*/
/*public OrderService(OrderDao orderDao) {
this.orderDao = orderDao;
}*/
@Autowired
public void setOrderDao(OrderDao orderDao) {
this.orderDao = orderDao;
}
public void generate(){
orderDao.insert();
}
}
再次运行:

以上程序OrderDao接口只有一个实现类,如果是多个呢?
在impl再创建一个实现类:
@Repository
public class OrderDaoImplForOracle implements OrderDao {
@Override
public void insert() {
System.out.println("Oracle正在保存订单信息");
}
}
回到OrderService,发现报错了

怎么解决这个问题呢?当然要byName,根据名称进行装配了。
@Autowired注解默认根据类型注入。如果要根据名称注入的话,需要配合@Qualifier注解一起使用。
@Qualifier源码
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Qualifier {
String value() default "";
}
可见与@Autowired用法差不多,只是属性名是value,表示指定Bean名称,就能更加名称自动装配了。
修改OrderService类:添加@Qualifier注解
@Service
public class OrderService {
@Autowired
@Qualifier("orderDaoImplForMysql")
private OrderDao orderDao;
public void generate(){
orderDao.insert();
}
}
再次运行测试程序:

如果想使用其他实现类,修改@Qualifier注解的value即可
@Service
public class OrderService {
@Autowired
//@Qualifier("orderDaoImplForMysql")
@Qualifier("orderDaoImplForOracle")
private OrderDao orderDao;
public void generate(){
orderDao.insert();
}
}
再次运行测试程序:

@Resource源码
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(Resources.class)
public @interface Resource {
String name() default "";
String lookup() default "";
Class<?> type() default Object.class;
Resource.AuthenticationType authenticationType() default Resource.AuthenticationType.CONTAINER;
boolean shareable() default true;
String mappedName() default "";
String description() default "";
public static enum AuthenticationType {
CONTAINER,
APPLICATION;
private AuthenticationType() {
}
}
}
很多属性,我们只关注name属性:用来接收Bean的名称的,未指定时默认根据属性名作为name。
@Resource注解也可以完成非简单类型注入。那它和@Autowired注解有什么区别?
区别一:
区别二:
区别三:
@Resource注解属于JDK扩展包,所以不在JDK当中,需要额外引入以下依赖:【如果是JDK8的话不需要额外引入依赖。高于JDK11或低于JDK8需要引入以下依赖。】
如果是spring6+版本使用这个依赖
<dependency>
<groupId>jakarta.annotation</groupId>
<artifactId>jakarta.annotation-api</artifactId>
<version>2.1.1</version>
</dependency>
如果是spring5-版本使用这个依赖
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
创建bean5包
创建spring-resource.xml配置:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.annotation.bean5"/>
</beans>
创建dao包
创建StudentDao接口
public interface StudentDao {
void deleteById();
}
创建impl包
创建两个实现类:
@Repository("studentDaoMysql")
public class StudentDaoImplForMysql implements StudentDao {
@Override
public void deleteById() {
System.out.println("Mysql正在删除学生信息。。。");
}
}
@Repository("studentDaoOracle")
public class StudentDaoImplForOracle implements StudentDao {
@Override
public void deleteById() {
System.out.println("Oracle正在删除学生信息。。。");
}
}
创建service包
创建StudentService类
@Service("studentService")
public class StudentService {
@Resource(name = "studentDaoMysql")
private StudentDao studentDaoMysql;
public void deleteStudent(){
studentDaoMysql.deleteById();
}
}
测试程序:
@Test
public void testByResource(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-resource.xml");
StudentService studentService = applicationContext.getBean("studentService", StudentService.class);
studentService.deleteStudent();
}

如果把name去掉,再次运行程序:

如果把属性名改为别的
@Service("studentService")
public class StudentService {
//@Resource(name = "studentDaoMysql")
@Resource
private StudentDao studentDao;
//private StudentDao studentDaoMysql;
public void deleteStudent(){
studentDao.deleteById();
//studentDaoMysql.deleteById();
}
}
再次运行:报错,所以说,不指定name时,默认会以属性名作为name,如果再找不到Bean,会切换成通过类型byType装配,而我们又有两个实现类,所以报错。

所谓的全注解开发就是不再使用spring配置文件了。需要写一个配置类来代替配置文件。
使用@Configuration注解代替
@Configuration//代表配置文件
@ComponentScan({"com.annotation.bean5"})//这里代表context:component-scan标签
public class Spring6Config {
}
编写测试程序:不再new ClassPathXmlApplicationContext()对象了,new的是AnnotationConfigApplicationContext()对象
@Test
public void testByNoXML(){
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Spring6Config.class);
StudentService studentService = applicationContext.getBean("studentService", StudentService.class);
studentService.deleteStudent();
}
