• (十二)Spring IoC注解式开发



    Spring学习目录

    上一篇:(十一)手写简单的Spring框架

    下一篇:(十三)Spring之JdbcTemplate

    回顾注解

    注解的存在主要是为了简化XML的配置。Spring6倡导全注解开发。
    我们来回顾一下:

    • 第一:注解怎么定义,注解中的属性怎么定义?
    • 第二:注解怎么使用?
    • 第三:通过反射机制怎么读取注解?

    注解怎么定义,注解中的属性怎么定义?

    注解使用@interface定义,注解中的属性与接口的方法的定义一样。
    自定义一个注解Component

    @Target(ElementType.TYPE_USE)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface Component {
        String value();
        //String name();
        //int[] ages();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    元注解

    该注解上面修饰的注解包括:Target注解和Retention注解,这两个注解被称为元注解。

    @Target注解

    @Target注解用来修饰注解可以出现的位置。只有一个属性,是一个value,且类型是一个枚举类型。
    具体值:

    • ElementType.TYPE:能修饰类、接口或枚举类型
    • ElementType.FIELD:能修饰成员变量
    • ElementType.METHOD:能修饰方法
    • ElementType.PARAMETER:能修饰参数
    • ElementType.CONSTRUCTOR:能修饰构造器
    • ElementType.LOCAL_VARIABLE:能修饰局部变量
    • ElementType.ANNOTATION_TYPE:能修饰注解
    • ElementType.PACKAGE:能修饰包
    • ElementType.RECORD_COMPONENT:与记录相关,是Java语言的预览功能。
    • ElementType.TYPE_PARAMETER:类型参数,是用在泛型类型 “T” 上的,是JDK8新推出的
    • ElementType.TYPE_USE:类型的注解,表示这个注解可以在任意地方使用(如:泛型,类型转换等),是JDK8新推出的
    @Retention注解

    @Retention用来标注注解最终保留位置,同样只有一个属性,是一个value,且类型是一个枚举类型。
    具体值:

    • RetentionPolicy.SOURCE 注解仅存在于源码中,在class字节码文件中不包含
    • RetentionPolicy.CLASS 默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得
    • RetentionPolicy.RUNTIME 注解会在class字节码文件中存在,在运行时可以通过反射获取到

    注解怎么使用?

    使用注解的语法:

    • @注解名(属性名 = 属性值,属性名 = 属性值,属性名 = 属性值…)

    使用某个注解的时候,属性名是value,value可以省略
    如果属性值是一个数组,并且值只有一个,那么{}可以省略

    //@Component(value = "userBean")
    @Component("userBean")
    public class User {
    }
    
    • 1
    • 2
    • 3
    • 4

    通过反射机制怎么读取注解?

    步骤:

    • 1.通过全限定类名获取类
    • 2.判断类上面有没有这个注解
    • 3.有则获取类上的注解
    • 4.访问注解属性
    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());
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    请添加图片描述

    Spring注解原理

    • 1.只知道包的名字,这个包下有多少个Bean我们不知道
    • 2.扫描这个包下所有的类
    • 3.当这个包下的类有注解的时候,实例化该类对象
    • 4.放到一个Map集合当中

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

    @Component("orderBean")
    public class Order {
    }
    
    • 1
    • 2
    • 3

    Products类:

    public class Products {
    }
    
    
    • 1
    • 2
    • 3

    原理程序:

    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);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41

    请添加图片描述

    声明Bean的注解

    负责声明Bean的注解,常见的包括四个:

    • @Component
    • @Controller
    • @Service
    • @Repository

    源码如下:
    @Component:

    @Target(value = {ElementType.TYPE})
    @Retention(value = RetentionPolicy.RUNTIME)
    public @interface Component {
        String value();
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    @Controller:

    @Target({ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Component
    public @interface Controller {
        @AliasFor(
            annotation = Component.class
        )
        String value() default "";
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    @Service注解:

    @Target({ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Component
    public @interface Service {
        @AliasFor(
            annotation = Component.class
        )
        String value() default "";
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    @Repository:

    @Target({ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Component
    public @interface Repository {
        @AliasFor(
            annotation = Component.class
        )
        String value() default "";
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    通过源码可以看到,@Controller、@Service、@Repository这三个注解都是@Component注解的别名。
    也就是说:这四个注解的功能都一样。用哪个都可以。
    只是为了增强程序的可读性,建议:

    • 控制器类上使用:Controller
    • service类上使用:Service
    • dao类上使用:Repository

    如果把value属性彻底去掉,spring会自动取名,并且默认名字的规律是:Bean类名首字母小写即可。

    Spring注解的使用

    如何使用以上的注解呢?

    • 第一步:加入aop的依赖
    • 第二步:在配置文件中添加context命名空间
    • 第三步:在配置文件中指定扫描的包
    • 第四步:在Bean类上使用注解

    第一步:加入aop的依赖

    在Maven项目中,当加入spring-context依赖之后,会关联加入aop的依赖。所以这一步不用做。如果不是Maven项目,则需要把jar包导进库。

    第二步:在配置文件中添加context命名空间

    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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    第三步:在配置文件中指定要扫描的包

    spring.xml添加指定要扫描的包:

    	<context:component-scan base-package="com.annotation.bean"/>
    
    • 1

    如果是多个包怎么办?有两种解决方案:

    • 第一种:在配置文件中指定多个包,用逗号隔开。
    • 第二种:指定多个包的共同父包,这种方式会牺牲一部分效率。

    第四步:在Bean类上使用注解

    四个注解都用一下,在bean包下创建四个类

    @Controller注解使用:创建User类

    //@Controller 不写value的话,默认是user,就是类名首字母小写
    @Controller(value = "user")
    public class User {
    }
    
    • 1
    • 2
    • 3
    • 4

    @Service注解使用:创建Student类

    @Service("studentBean")
    public class Student {
    }
    
    • 1
    • 2
    • 3

    @Repository使用:创建Order类

    @Repository("orderBean")
    public class Order {
    }
    
    • 1
    • 2
    • 3

    @Component使用:创建Car类

    @Component("carBean")
    public class Car {
    }
    
    • 1
    • 2
    • 3

    测试程序:

    @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);  
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    请添加图片描述

    选择性实例化Bean

    假设在某个包下有很多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标签

        • type属性:需要失效的类型
        • expression:需要失效的全限定路径
    • use-default-filters="false"表示:不再spring默认实例化规则,即使有Component、Controller、Service、Repository这些注解标注,也不再实例化。

      • 如果设置成false后,想让其生效需要添加一个context:include-filter标签使特定的注解生效

        • type属性:需要生效的类型

        • expression:需要生效的全限定路径

    这两种方式类似于黑名单和白名单
    注意:因为Component注解是其他三个注解的”老大“,所以

    • 如果是默认值或者true,让其Component失效,会连其三个注解全部失效。
    • 如果设置成false,让其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的无参数构造方法执行。。。");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    创建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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    use-default-filters="true"情况

    让其@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>
    
    • 1
    • 2
    • 3

    测试程序:因为只需要测试是否实例化,不用获取Bean

        @Test
        public void testBeanChoose(){
            ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-choose.xml");
        }
    
    • 1
    • 2
    • 3
    • 4

    运行发现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>
    
    • 1
    • 2
    • 3

    再次运行测试程序:全都不生效了
    请添加图片描述

    use-default-filters="false"情况

    记得上面的配置要注释掉,让其@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>
    
    • 1
    • 2
    • 3

    测试程序是同一个,再次运行: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>
    
    • 1
    • 2
    • 3

    再次运行测试程序:全都生效
    请添加图片描述

    负责注入的注解

    @Component @Controller @Service @Repository 这四个注解是用来声明Bean的,声明后这些Bean将被实例化。如何给Bean的属性赋值。给Bean属性赋值需要用到这些注解:

    • @Value
    • @Autowired
    • @Qualifier
    • @Resource

    @Value

    @Value注解的源码

    @Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface Value {
        String value();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    只负责简单类型的注入,属性名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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    声明在属性上

    在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 +
                    '}';
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    测试程序:

        @Test
        public void testByValue(){
            ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-value.xml");
            User1 user1 = applicationContext.getBean("user1", User1.class);
            System.out.println(user1);
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    请添加图片描述
    删掉setter方法,再次运行测试程序:发现声明在属性上可以不提供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;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    在上面测试程序添加:

    		User2 user2 = applicationContext.getBean("user2", User2.class);
            System.out.println(user2);
    
    • 1
    • 2

    请添加图片描述

    声明构造方法的参数上

    在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;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    在上面测试程序添加:

    		User3 user3 = applicationContext.getBean("user3", User3.class);
            System.out.println(user3);
    
    • 1
    • 2

    请添加图片描述

    @Autowired与@Qualifier

    @Autowired 与 @Qualifier:Autowired翻译为:自动连线/自动装配,可以用来注入非简单类型

    • 单独使用@Autowired注解,默认只能根据类型自动装配【默认是byType】
    • @Autowired 与 @Qualifier 联合使用可以根据名称自动装配

    创建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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    在bean4包下创建dao包,在dao包下创建一个OrderDao接口:

    public interface OrderDao {
        void insert();
    }
    
    
    • 1
    • 2
    • 3
    • 4

    在dao包下创建impl包,提供一个实现类:

    @Repository
    public class OrderDaoImplForMysql implements OrderDao {
        @Override
        public void insert() {
            System.out.println("Mysql正在保存订单信息");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    创建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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    @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();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    测试程序:

        @Test
        public void testByAutowired(){
            ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-autowired.xml");
            OrderService orderService = applicationContext.getBean("orderService", OrderService.class);
            orderService.generate();
        }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    在这里插入图片描述
    删掉setter方法,再次运行测试程序:发现声明在属性上可以不提供setter方法。
    请添加图片描述

    声明在构造方法上

    修改OrderService类:

    @Service
    public class OrderService {
        /*@Autowired*/
        private OrderDao orderDao;
        @Autowired
        public OrderService(OrderDao orderDao) {
            this.orderDao = orderDao;
        }
    
        public void generate(){
            orderDao.insert();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    与上面相同的测试程序,再次运行:
    请添加图片描述

    声明在构造方法的参数上
    @Service
    public class OrderService {
        /*@Autowired*/
        private OrderDao orderDao;
        /*@Autowired*/
        public OrderService(@Autowired OrderDao orderDao) {
            this.orderDao = orderDao;
        }
    
        public void generate(){
            orderDao.insert();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    再次运行测试程序:
    请添加图片描述
    当带参数的构造方法只有一个,@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();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    再次运行:报错,当带参数的构造方法只能有一个,有无参构造也不行,这个可以自己测试。
    请添加图片描述

    声明在setter方法上
    @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();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    再次运行:
    请添加图片描述

    根据名称自动装配

    以上程序OrderDao接口只有一个实现类,如果是多个呢?
    在impl再创建一个实现类:

    @Repository
    public class OrderDaoImplForOracle implements OrderDao {
        @Override
        public void insert() {
            System.out.println("Oracle正在保存订单信息");
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    回到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 "";
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    可见与@Autowired用法差不多,只是属性名是value,表示指定Bean名称,就能更加名称自动装配了。

    修改OrderService类:添加@Qualifier注解

    @Service
    public class OrderService {
        @Autowired
        @Qualifier("orderDaoImplForMysql")
        private OrderDao orderDao;
        public void generate(){
            orderDao.insert();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    再次运行测试程序:
    请添加图片描述
    如果想使用其他实现类,修改@Qualifier注解的value即可

    @Service
    public class OrderService {
        @Autowired
        //@Qualifier("orderDaoImplForMysql")
        @Qualifier("orderDaoImplForOracle")
        private OrderDao orderDao;
        public void generate(){
            orderDao.insert();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    再次运行测试程序:
    请添加图片描述

    总结

    • @Autowired注解可以出现在:属性上、构造方法上、构造方法的参数上、setter方法上。
    • 注解如果声明在属性上可以不提供setter方法,当带参数的构造方法只有一个,@Autowired注解可以省略。
    • @Autowired注解默认根据类型注入。如果要根据名称注入的话,需要配合@Qualifier注解一起使用。

    @Resource

    @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() {
            }
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    很多属性,我们只关注name属性:用来接收Bean的名称的,未指定时默认根据属性名作为name。
    @Resource注解也可以完成非简单类型注入。那它和@Autowired注解有什么区别?

    • 区别一:

      • @Resource注解是JDK扩展包中的,也就是说属于JDK的一部分。所以该注解是标准注解,更加具有通用性。(JSR-250标准中制定的注解类型。JSR是Java规范提案。)
      • @Autowired注解是Spring框架自己的。
    • 区别二:

      • @Resource注解默认根据名称装配byName,未指定name时,使用属性名作为name。通过name找不到的话会自动启动通过类型byType装配。
      • @Autowired注解默认根据类型装配byType,如果想根据名称装配,需要配合@Qualifier注解一起用。
    • 区别三:

      • @Resource注解用在属性上、setter方法上。
      • @Autowired注解用在属性上、setter方法上、构造方法上、构造方法参数上。

    @Resource注解属于JDK扩展包,所以不在JDK当中,需要额外引入以下依赖:【如果是JDK8的话不需要额外引入依赖。高于JDK11或低于JDK8需要引入以下依赖。】
    如果是spring6+版本使用这个依赖

    <dependency>
      <groupId>jakarta.annotation</groupId>
      <artifactId>jakarta.annotation-api</artifactId>
      <version>2.1.1</version>
    </dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    如果是spring5-版本使用这个依赖

    <dependency>
      <groupId>javax.annotation</groupId>
      <artifactId>javax.annotation-api</artifactId>
      <version>1.3.2</version>
    </dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    创建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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    创建dao包
    创建StudentDao接口

    public interface StudentDao {
        void deleteById();
    }
    
    • 1
    • 2
    • 3

    创建impl包
    创建两个实现类:

    @Repository("studentDaoMysql")
    public class StudentDaoImplForMysql implements StudentDao {
    
        @Override
        public void deleteById() {
            System.out.println("Mysql正在删除学生信息。。。");
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    @Repository("studentDaoOracle")
    public class StudentDaoImplForOracle implements StudentDao {
    
        @Override
        public void deleteById() {
            System.out.println("Oracle正在删除学生信息。。。");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    创建service包
    创建StudentService类

    @Service("studentService")
    public class StudentService {
        @Resource(name = "studentDaoMysql")
        
        private StudentDao studentDaoMysql;
        
    
        public void deleteStudent(){
           studentDaoMysql.deleteById();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    测试程序:

        @Test
        public void testByResource(){
            ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-resource.xml");
            StudentService studentService = applicationContext.getBean("studentService", StudentService.class);
            studentService.deleteStudent();
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    请添加图片描述
    如果把name去掉,再次运行程序:
    请添加图片描述

    如果把属性名改为别的

    @Service("studentService")
    public class StudentService {
        //@Resource(name = "studentDaoMysql")
        @Resource
        private StudentDao studentDao;
        //private StudentDao studentDaoMysql;
    
        public void deleteStudent(){
            studentDao.deleteById();
            //studentDaoMysql.deleteById();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    再次运行:报错,所以说,不指定name时,默认会以属性名作为name,如果再找不到Bean,会切换成通过类型byType装配,而我们又有两个实现类,所以报错。
    请添加图片描述

    全注解式开发

    所谓的全注解开发就是不再使用spring配置文件了。需要写一个配置类来代替配置文件。
    使用@Configuration注解代替

    @Configuration//代表配置文件
    @ComponentScan({"com.annotation.bean5"})//这里代表context:component-scan标签
    public class Spring6Config {
    }
    
    • 1
    • 2
    • 3
    • 4

    编写测试程序:不再new ClassPathXmlApplicationContext()对象了,new的是AnnotationConfigApplicationContext()对象

        @Test
        public void testByNoXML(){
            ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Spring6Config.class);
            StudentService studentService = applicationContext.getBean("studentService", StudentService.class);
            studentService.deleteStudent();
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    请添加图片描述

  • 相关阅读:
    深度学习-第一章-Window下用Anaconda安装Yolov5
    CI2454集成2.4G收发SOC【遥控;灯具;玩具】技术开发资料
    openpose环境基于opencv4.4 +cuda11.3+cudnn8.X
    【初识JavaScript-运算符总合】
    QT画图功能
    Java----HashSet集合、equals(判断两个字符串是否相等)、LinkedHashSet集合、迭代器、可变参数
    IDEA常用快捷键总结(Windows)
    Java和JavaScript区别与联系
    Worthington果胶酶的特性及测定方案
    泰国放宽MogaFX外汇经营商规则
  • 原文地址:https://blog.csdn.net/weixin_45832694/article/details/127988392