一、SpringIOC基于注解的方式进行注入:通过设计模式+反射机制来模拟注入过程
1、spring的配置文件:beans.xml:开启扫描包的过程,spring会去扫描该包下所有子类,为了检查有没有spring提供的注解。
2、要在指定的类上加注解,如果spring检查到该类上有注解,就将该类的实例通过反射机制创建出来,装进spring中。
3、会检查该类中的属性上有没有spring提供的注解,如果有的话,会通过反射的方式去注入实例。
二、基于注解的方式创建核心容器对象
spring 5.0版本后支持注解的方式创建核心容器对象,这样我们的程序就可以脱离xml配置文件。
@Configuration:声明当前类是一个配置类。
@ComponentScan:开启扫描包
@Bean:
类似于xml中的bean标签,标识可以自定义,用于修饰方法,可以将修饰方法的返回值作为一份实例装载到spring容器中,给属性注入数据时可以直接使用set方法。
@Configurationpublic class SpringConfig {@Beanpublic User getUser(Student stu1){User user = new User();user.setId(1);user.setName("zs");user.setPassword("123123");return user;}@Bean("stu1")public Student getStu1(){return new Student();}}
而且修饰方法的参数实例会从容器中去匹配,匹配的规则与@Autowired 一样,都是根据类型匹配,如果同一类型有多个,根据标识即@Bean的参数,默认是类名全小写,也可以自定义,如下面的@Bean(“stu1”)与@Bean(“stu2”),还可以结合@Qualifier。
@Configurationpublic class SpringConfig {@Beanpublic User getUser(Student stu1){User user = new User();user.setId(1);user.setName("zs");user.setPassword("123123");user.setStudent(student);return user;}/*@Beanpublic User getUser(@Qualifier("getStu1") Student student){return new User();}*/@Bean("stu1")public Student getStu1(){Student student = new Student();student.setId(100);student.setName("张三");return student;}@Bean("stu2")public Student getStu2(){Student student = new Student();student.setId(101);student.setName("李四");return student;}}
运行结果:
@PropertySource:引入配置文件
新建一个配置文件jdbc.properties
@Configuration@PropertySource("classpath:jdbc")public class JDBCConfig {@Value("${jdbc_username}")private String username;@Value("${jdbc_password}")private String password;@Bean("user")public User getUser(){User user = new User();user.setName(username);user.setPassword(password);return user;}}
@Import:引入其他核心配置类
