Spring注解驱动开发
容器 (IOC)
-
AnnotationConfigApplication
-
配置文件
<beans> // 扫描注解@Controller、@Service、@Repository、@Component标记的类注册到容器中 <context:component-csan base-package="com.example"></context:component-csan // 注册组件 <bean id="person" class="com.example.Person"> <property name="name" value="lisi"> </property > <property name="age" value="18"> </property > </bean> </beans>
public static void main(String[] args) { ApplicationContext ioc = new ClassPathXmlApplicationContext("beans.xml"); Person person = (Person)ioc.getBean("person"); }
-
配置类
@Configuration @ComponentScan(value = "com.example",excludeFilters = { @Filter(type = FilterType.ANNOTATION,classes = {Controller.class,Service.class})} ,includeFilters = { @Filter(type = FilterType.ANNOTATION,classes = {Controller.class,Service.class}, useDefaultFilters = false), @Filter(type = FilterType.ASSIGNABLE_TYPE ,classes ={PersonController.class}, useDefaultFilters = false) } ) public class MainConfig { @Bean(value="person1") public Person person() { return new Person("lisi",20); } }
public static void main(String[] args) { ApplicationContext ioc = new AnnotationConfigApplication(MainConfig.class); Person person = (Person)ioc.getBean(Person.class); }
扫描规则
-
ANNOTATION --注解
-
ASSIGNABLE_TYPE --指定类型
-
ASPECTJ --切面
-
REGEX --正则表达式
-
CUSTOM --自定义规则
-
-
-
组件注册
-
@ComponentScan+组件标注注解@Controller/@Service/@Repository/@Component[导入自定义组件]
-
@Configuration+@Bean[注册第三方包里面的组件]
-
@Import[快速把组件注册到容器中]
-
@Import(要注册到容器中的组件):容器会自动注册单个组件,默认id是全限定类名
@Import(value={Red.class, CImportSelector.class, CImportBeanDefinitionRegister.class}) @Configuration public class MainConfig2 { @Bean public Person person() { return new Person("W",22); } }
-
@ImportSelector:返回与需要注册组件的的全限定类名数组,默认id是全限定类名
/** * 将Blue和Yellow组件注册到容器中 */ public class Selector implements ImportSelector { public String[] selectImports(AnnotationMetadata annotationMetadata) { return new String[]{"com.example.bean.Blue","com.example.bean.Yellow"}; } }
-
ImportBeanDefinitionRegistory:手动注册Bean到容器中,可以指定id
/** * @Description: 重写registerBeanDefinitions方法 * @Param: [annotationMetadata:当前类的注解信息, beanDefinitionRegistry:注册类] * @return: void * @Author: Qiao * @Date: 2019/10/4 */ public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) { boolean red = beanDefinitionRegistry.containsBeanDefinition("com.example.bean.Red"); boolean blue = beanDefinitionRegistry.containsBeanDefinition("com.example.bean.Blue"); if (red && blue) { beanDefinitionRegistry.registerBeanDefinition("rainBow", new RootBeanDefinition(RainBow.class)); } }
-
-
使用Spring提供的FactoryBean(工厂Bean)
package org.springframework.beans.factory; import org.springframework.lang.Nullable; public interface FactoryBean<T> { @Nullable T getObject() throws Exception; @Nullable Class<?> getObjectType(); default boolean isSingleton() { return true; } } /** *1.实现FactoryBean接口 *2.重写三个方法 *3.将自定义的工厂组件注册到容器中 */
-
测试方法
@Test public void test02() { AnnotationConfigApplicationContext ioc = new AnnotationConfigApplicationContext(MainConfig2.class); String[] beanDefinitionNames = ioc.getBeanDefinitionNames(); for (String name:beanDefinitionNames) { System.out.println(name); } }
-
-
组件赋值
- @value
-
组件注入(DI)
- @Autowired 自动装配
- 构造器注入
- 接口注入
- set注入
- @Resource
- @Inject
- @Autowired 自动装配
-
生命周期
- 创建
- 单实例:容器启动时将组件注册到容器中
- 多实例:使用组件时才将组件注册到容器中(每调用一次注册一次)
- BeanPostProcessor.postProcessBeforeInitialization
- 初始化
对象创建完成,并赋值后调用初始化方法 - BeanPostProcessor.postProcessAfterInitialization
- 销毁
- 单实例:容器关闭的时候。
- 多实例:容器不会管理这个bean,容器不会调用销毁方法
我们可以自定义初始化和销毁方法;容器在bean进行到当前生命周期时来调用我们自定义的初始化和销毁方法.
下面介绍四种管理bean生命周期的方法:
- 指定初始化和销毁方法
- 基于配置文件
<bean id="person" class="com.example.Person" init-method="" destory-method=""> <property name="name" value="lisi"> </property > <property name="age" value="18"> </property > </bean>
- 配置类
package com.example.baen; @Slf4j public class Car { public Car() { log.info("car constructor...."); } public void init() { log.info("car init...."); } public void destory() { log.info("car destory...."); } } package com.example.config; @Configuration public class MainConfigOfLifeCycle { @Bean(initMethod="init",destoryMethod="destory") public Car car() { return new Car(); } } // 对于单实例来说容器关闭时调用销毁方法
- 基于配置文件
- 通过让Bean实现InitializingBean(定义初始化逻辑)、DisposableBean(定义销毁逻辑)
- 使用JSR250规范中的@PostConstruct、@PreDestory
- BeanPostProcessor:在初始化前后被调用
- 创建