【Spring】Spring常用注解(中)

简介: 【Spring】Spring常用注解(中)
IOCTest
1. public class IOCTest {
2.    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig2.class);
3. 
4. 
5.    @Test
6.    public void testImport(){
7.       printBeans(applicationContext);
8.       Blue bean = applicationContext.getBean(Blue.class);
9.       System.out.println(bean);
10. 
11. //工厂Bean获取的是调用getObject创建的对象
12. Object bean2 = applicationContext.getBean("colorFactoryBean");   
13.       System.out.println("bean的类型:"+bean2.getClass()); //pos_1   输出:bean的类型:class com.atguigu.bean.Color
14. 
15. Object bean4 = applicationContext.getBean("&colorFactoryBean");
16.       System.out.println(bean4.getClass()); //pos_2  输出:class com.atguigu.bean.ColorFactoryBean
17.    }
18. 
19.    private void printBeans(AnnotationConfigApplicationContext applicationContext){
20. String[] definitionNames = applicationContext.getBeanDefinitionNames();
21. for (String name : definitionNames) {
22.          System.out.println(name);
23.       }
24.    }
25. }

输出:

//前面无关的输出省略


colorFactoryBean

ColorFactoryBean...getObject...

bean的类型:class com.atguigu.bean.Color

class com.atguigu.bean.ColorFactoryBean

生命周期

@Bean指定初始化和销毁方法

IOCTest_LifeCycle

后面的几个用的都是这个测试类

1. public class IOCTest_LifeCycle {
2. 
3.    @Test
4.    public void test01(){
5. //1、创建ioc容器
6.       AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfLifeCycle.class);
7.       System.out.println("容器创建完成...");
8. 
9. //applicationContext.getBean("car");
10. //关闭容器
11.       applicationContext.close();
12.    }
13. 
14. }
MainConfigOfLifeCycle
1. package com.atguigu.config;
2. 
3. import org.springframework.context.ApplicationListener;
4. import org.springframework.context.annotation.Bean;
5. import org.springframework.context.annotation.ComponentScan;
6. import org.springframework.context.annotation.Configuration;
7. import org.springframework.context.annotation.Scope;
8. 
9. import com.atguigu.bean.Car;
10. 
11. /**
12.  * bean的生命周期:
13.  *        bean创建---初始化----销毁的过程
14.  * 容器管理bean的生命周期;
15.  * 我们可以自定义初始化和销毁方法;容器在bean进行到当前生命周期的时候来调用我们自定义的初始化和销毁方法
16.  * 
17.  * 构造(对象创建)
18.  *        单实例:在容器启动的时候创建对象
19.  *        多实例:在每次获取的时候创建对象\
20.  * 初始化:
21.  *    对象创建完成,并赋值好,调用初始化方法。。。
22.  * BeanPostProcessor.postProcessAfterInitialization
23.  * 销毁:
24.  *    单实例:容器关闭的时候
25.  *    多实例:容器不会管理这个bean;容器不会调用销毁方法;
26.  * 
27.  * 1)、指定初始化和销毁方法;
28.  *        通过@Bean指定init-method和destroy-method;
29.  * @author lfy
30.  *
31.  */
32. @ComponentScan("com.atguigu.bean")
33. @Configuration
34. public class MainConfigOfLifeCycle {
35. 
36. //@Scope("prototype")
37. @Bean(initMethod="init",destroyMethod="detory")
38. public Car car(){
39. return new Car();
40.    }
41. 
42. }
43. @Component
44. public class Car {
45. 
46. public Car(){
47.       System.out.println("car constructor...");
48.    }
49. 
50. public void init(){
51.       System.out.println("car ... init...");
52.    }
53. 
54. public void detory(){
55.       System.out.println("car ... detory...");
56.    }
57. 
58. }
输出

car constructor...

car ... init...

容器创建完成

car ... detory...

InitializingBean和DisposableBean

MainConfigOfLifeCycle
1. /**
2.  * bean的生命周期:
3.  *        bean创建---初始化----销毁的过程
4.  * 容器管理bean的生命周期;
5.  * 我们可以自定义初始化和销毁方法;容器在bean进行到当前生命周期的时候来调用我们自定义的初始化和销毁方法
6.  * 
7.  * 构造(对象创建)
8.  *        单实例:在容器启动的时候创建对象
9.  *        多实例:在每次获取的时候创建对象\
10.  * 
11.  * BeanPostProcessor.postProcessBeforeInitialization
12.  * 初始化:
13.  *        对象创建完成,并赋值好,调用初始化方法。。。
14.  * BeanPostProcessor.postProcessAfterInitialization
15.  * 销毁:
16.  *        单实例:容器关闭的时候
17.  *        多实例:容器不会管理这个bean;容器不会调用销毁方法;
18.  * 
19.  * 
20.  * 遍历得到容器中所有的BeanPostProcessor;挨个执行beforeInitialization,
21.  * 一但返回null,跳出for循环,不会执行后面的BeanPostProcessor.postProcessorsBeforeInitialization
22.  * 
23.  * BeanPostProcessor原理
24.  * populateBean(beanName, mbd, instanceWrapper);给bean进行属性赋值
25.  * initializeBean
26.  * {
27.  * applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
28.  * invokeInitMethods(beanName, wrappedBean, mbd);执行自定义初始化
29.  * applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
30.  *}
31.  * 
32.  * 
33.  * 
34.  * 1)、指定初始化和销毁方法;
35.  *        通过@Bean指定init-method和destroy-method;
36.  * 2)、通过让Bean实现InitializingBean(定义初始化逻辑),
37.  *              DisposableBean(定义销毁逻辑);
38.  * 
39.  * @author lfy
40.  *
41.  */
42. @ComponentScan("com.atguigu.bean")
43. @Configuration
44. public class MainConfigOfLifeCycle {
45. 
46. //@Scope("prototype")
47.    @Bean(initMethod="init",destroyMethod="detory")
48.    public Car car(){
49. return new Car();
50.    }
51. 
52. }
Cat
1. @Component
2. public class Cat implements InitializingBean,DisposableBean {
3. 
4. public Cat(){
5.       System.out.println("cat constructor...");
6.    }
7. 
8.    @Override
9. public void destroy() throws Exception {
10. // TODO Auto-generated method stub
11.       System.out.println("cat...destroy...");
12.    }
13. 
14.    @Override
15. public void afterPropertiesSet() throws Exception {
16. // TODO Auto-generated method stub
17.       System.out.println("cat...afterPropertiesSet...");
18.    }
19. 
20. }
输出

cat constructor...

cat...afterPropertiesSet...

car constructor...

car ... init...

容器创建完成

car ... detory...

cat...destroy...

@PostConstruct和@PreDestroy

MainConfigOfLifeCycle
1. /**
2.  * bean的生命周期:
3.  *        bean创建---初始化----销毁的过程
4.  * 容器管理bean的生命周期;
5.  * 我们可以自定义初始化和销毁方法;容器在bean进行到当前生命周期的时候来调用我们自定义的初始化和销毁方法
6.  * 
7.  * 构造(对象创建)
8.  *        单实例:在容器启动的时候创建对象
9.  *        多实例:在每次获取的时候创建对象\
10.  * 
11.  * BeanPostProcessor.postProcessBeforeInitialization
12.  * 初始化:
13.  *        对象创建完成,并赋值好,调用初始化方法。。。
14.  * BeanPostProcessor.postProcessAfterInitialization
15.  * 销毁:
16.  *        单实例:容器关闭的时候
17.  *        多实例:容器不会管理这个bean;容器不会调用销毁方法;
18.  * 
19.  * 
20.  * 遍历得到容器中所有的BeanPostProcessor;挨个执行beforeInitialization,
21.  * 一但返回null,跳出for循环,不会执行后面的BeanPostProcessor.postProcessorsBeforeInitialization
22.  * 
23.  * BeanPostProcessor原理
24.  * populateBean(beanName, mbd, instanceWrapper);给bean进行属性赋值
25.  * initializeBean
26.  * {
27.  * applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
28.  * invokeInitMethods(beanName, wrappedBean, mbd);执行自定义初始化
29.  * applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
30.  *}
31.  * 
32.  * 
33.  * 
34.  * 1)、指定初始化和销毁方法;
35.  *        通过@Bean指定init-method和destroy-method;
36.  * 2)、通过让Bean实现InitializingBean(定义初始化逻辑),
37.  *              DisposableBean(定义销毁逻辑);
38.  * 3)、可以使用JSR250;
39.  *        @PostConstruct:在bean创建完成并且属性赋值完成;来执行初始化方法
40.  *        @PreDestroy:在容器销毁bean之前通知我们进行清理工作
41.  * 
42.  * @author lfy
43.  *
44.  */
45. @ComponentScan("com.atguigu.bean")
46. @Configuration
47. public class MainConfigOfLifeCycle {
48. 
49. //@Scope("prototype")
50.    @Bean(initMethod="init",destroyMethod="detory")
51.    public Car car(){
52. return new Car();
53.    }
54. 
55. }
Dog
1. @Component
2. public class Dog implements ApplicationContextAware {
3. 
4. //@Autowired
5. private ApplicationContext applicationContext;
6. 
7. public Dog(){
8.       System.out.println("dog constructor...");
9.    }
10. 
11. //对象创建并赋值之后调用
12.    @PostConstruct
13. public void init(){
14.       System.out.println("Dog....@PostConstruct...");
15.    }
16. 
17. //容器移除对象之前
18.    @PreDestroy
19. public void detory(){
20.       System.out.println("Dog....@PreDestroy...");
21.    }
22. 
23.    @Override
24. public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
25. // TODO Auto-generated method stub
26. this.applicationContext = applicationContext;
27.    }
28. }
输出
1. cat constructor...
2. cat...afterPropertiesSet...
3. dog constructor...
4. Dog....@PostConstruct...
5. car constructor...
6. car ... init...
7. 容器创建完成
8. car ... detory...
9. Dog....@PreDestroy...
10. cat...destroy...
11. BeanPostProcessor
12. /**
13.  * bean的生命周期:
14.  *        bean创建---初始化----销毁的过程
15.  * 容器管理bean的生命周期;
16.  * 我们可以自定义初始化和销毁方法;容器在bean进行到当前生命周期的时候来调用我们自定义的初始化和销毁方法
17.  * 
18.  * 构造(对象创建)
19.  *        单实例:在容器启动的时候创建对象
20.  *        多实例:在每次获取的时候创建对象\
21.  * 
22.  * BeanPostProcessor.postProcessBeforeInitialization
23.  * 初始化:
24.  *        对象创建完成,并赋值好,调用初始化方法。。。
25.  * BeanPostProcessor.postProcessAfterInitialization
26.  * 销毁:
27.  *        单实例:容器关闭的时候
28.  *        多实例:容器不会管理这个bean;容器不会调用销毁方法;
29.  * 
30.  * 
31.  * 遍历得到容器中所有的BeanPostProcessor;挨个执行beforeInitialization,
32.  * 一但返回null,跳出for循环,不会执行后面的BeanPostProcessor.postProcessorsBeforeInitialization
33.  * 
34.  * BeanPostProcessor原理
35.  * populateBean(beanName, mbd, instanceWrapper);给bean进行属性赋值
36.  * initializeBean
37.  * {
38.  * applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
39.  * invokeInitMethods(beanName, wrappedBean, mbd);执行自定义初始化
40.  * applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
41.  *}
42.  * 
43.  * 
44.  * 
45.  * 1)、指定初始化和销毁方法;
46.  *        通过@Bean指定init-method和destroy-method;
47.  * 2)、通过让Bean实现InitializingBean(定义初始化逻辑),
48.  *              DisposableBean(定义销毁逻辑);
49.  * 3)、可以使用JSR250;
50.  *        @PostConstruct:在bean创建完成并且属性赋值完成;来执行初始化方法
51.  *        @PreDestroy:在容器销毁bean之前通知我们进行清理工作
52.  * 4)、BeanPostProcessor【interface】:bean的后置处理器;
53.  *        在bean初始化前后进行一些处理工作;
54.  *        postProcessBeforeInitialization:在初始化之前工作
55.  *        postProcessAfterInitialization:在初始化之后工作
56.  * 
57.  * Spring底层对 BeanPostProcessor 的使用;
58.  *        bean赋值,注入其他组件,@Autowired,生命周期注解功能,@Async,xxx BeanPostProcessor;
59.  * 
60.  * @author lfy
61.  *
62.  */
63. @ComponentScan("com.atguigu.bean")
64. @Configuration
65. public class MainConfigOfLifeCycle {
66. 
67. //@Scope("prototype")
68.    @Bean(initMethod="init",destroyMethod="detory")
69.    public Car car(){
70. return new Car();
71.    }
72. 
73. }
MyBeanPostProcessor
1. /**
2.  * 后置处理器:初始化前后进行处理工作
3.  * 将后置处理器加入到容器中
4.  * @author lfy
5.  */
6. @Component
7. public class MyBeanPostProcessor implements BeanPostProcessor {
8. 
9.    @Override
10.    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
11. // TODO Auto-generated method stub
12.       System.out.println("postProcessBeforeInitialization..."+beanName+"=>"+bean);
13. return bean;
14.    }
15. 
16.    @Override
17.    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
18. // TODO Auto-generated method stub
19.       System.out.println("postProcessAfterInitialization..."+beanName+"=>"+bean);
20. return bean;
21.    }
22. 
23. }

输出

自己写的组件输出内容

car constructor... postProcessBeforeInitialization...car=>com.atguigu.bean.Car@5ef60048 car ... init... postProcessAfterInitialization...car=>com.atguigu.bean.Car@5ef60048 cat constructor... postProcessBeforeInitialization...cat=>com.atguigu.bean.Cat@780cb77 cat...afterPropertiesSet... postProcessAfterInitialization...cat=>com.atguigu.bean.Cat@780cb77 dog constructor... postProcessBeforeInitialization...dog=>com.atguigu.bean.Dog@4034c28c Dog....@PostConstruct... postProcessAfterInitialization...dog=>com.atguigu.bean.Dog@4034c28c 容器创建完成... Dog....@PreDestroy... cat...destroy... car ... detory...

  1. BeanPostProcessor在Spring源码里大量被使用到,仅凭这里雷丰阳老师讲的一点点原理,是无法体会的,建议自己去看看Spring源码。所以这里的原理部分我也就直接省略了,在本视频中讲的太浅了。

属性赋值

@Value和@PropertySource

Person
1. public class Person {
2. 
3. //使用@Value赋值;
4. //1、基本数值
5. //2、可以写SpEL; #{}
6. //3、可以写${};取出配置文件【properties】中的值(在运行环境变量里面的值)
7. 
8. @Value("张三")
9. private String name;
10. @Value("#{20-2}")
11. private Integer age;
12. 
13. @Value("${person.nickName}")
14. private String nickName;
15. 
16. 
17. 
18. public String getNickName() {
19. return nickName;
20.    }
21. public void setNickName(String nickName) {
22. this.nickName = nickName;
23.    }
24. public String getName() {
25. return name;
26.    }
27. public void setName(String name) {
28. this.name = name;
29.    }
30. public Integer getAge() {
31. return age;
32.    }
33. public void setAge(Integer age) {
34. this.age = age;
35.    }
36. 
37. public Person(String name, Integer age) {
38. super();
39. this.name = name;
40. this.age = age;
41.    }
42. public Person() {
43. super();
44. // TODO Auto-generated constructor stub
45.    }
46. @Override
47. public String toString() {
48. return "Person [name=" + name + ", age=" + age + ", nickName=" + nickName + "]";
49.    }
50. }
相关文章
|
9月前
|
XML 安全 Java
使用 Spring 的 @Aspect 和 @Pointcut 注解简化面向方面的编程 (AOP)
面向方面编程(AOP)通过分离横切关注点,如日志、安全和事务,提升代码模块化与可维护性。Spring 提供了对 AOP 的强大支持,核心注解 `@Aspect` 和 `@Pointcut` 使得定义切面与切入点变得简洁直观。`@Aspect` 标记切面类,集中处理通用逻辑;`@Pointcut` 则通过表达式定义通知的应用位置,提高代码可读性与复用性。二者结合,使开发者能清晰划分业务逻辑与辅助功能,简化维护并提升系统灵活性。Spring AOP 借助代理机制实现运行时织入,与 Spring 容器无缝集成,支持依赖注入与声明式配置,是构建清晰、高内聚应用的理想选择。
816 0
|
9月前
|
缓存 监控 Java
SpringBoot @Scheduled 注解详解
使用`@Scheduled`注解实现方法周期性执行,支持固定间隔、延迟或Cron表达式触发,基于Spring Task,适用于日志清理、数据同步等定时任务场景。需启用`@EnableScheduling`,注意线程阻塞与分布式重复问题,推荐结合`@Async`异步处理,提升任务调度效率。
1410 128
|
9月前
|
Java 测试技术 API
将 Spring 的 @Embedded 和 @Embeddable 注解与 JPA 结合使用的指南
Spring的@Embedded和@Embeddable注解简化了JPA中复杂对象的管理,允许将对象直接嵌入实体,减少冗余表与连接操作,提升数据库设计效率。本文详解其用法、优势及适用场景。
452 126
|
10月前
|
XML JSON Java
Spring框架中常见注解的使用规则与最佳实践
本文介绍了Spring框架中常见注解的使用规则与最佳实践,重点对比了URL参数与表单参数的区别,并详细说明了@RequestParam、@PathVariable、@RequestBody等注解的应用场景。同时通过表格和案例分析,帮助开发者正确选择参数绑定方式,避免常见误区,提升代码的可读性与安全性。
|
9月前
|
Java 测试技术 数据库
使用Spring的@Retryable注解进行自动重试
在现代软件开发中,容错性和弹性至关重要。Spring框架提供的`@Retryable`注解为处理瞬时故障提供了一种声明式、可配置的重试机制,使开发者能够以简洁的方式增强应用的自我恢复能力。本文深入解析了`@Retryable`的使用方法及其参数配置,并结合`@Recover`实现失败回退策略,帮助构建更健壮、可靠的应用程序。
1026 1
使用Spring的@Retryable注解进行自动重试
|
8月前
|
XML Java 应用服务中间件
【SpringBoot(一)】Spring的认知、容器功能讲解与自动装配原理的入门,带你熟悉Springboot中基本的注解使用
SpringBoot专栏开篇第一章,讲述认识SpringBoot、Bean容器功能的讲解、自动装配原理的入门,还有其他常用的Springboot注解!如果想要了解SpringBoot,那么就进来看看吧!
742 2
|
9月前
|
XML Java 数据格式
常用SpringBoot注解汇总与用法说明
这些注解的使用和组合是Spring Boot快速开发和微服务实现的基础,通过它们,可以有效地指导Spring容器进行类发现、自动装配、配置、代理和管理等核心功能。开发者应当根据项目实际需求,运用这些注解来优化代码结构和服务逻辑。
592 12
|
9月前
|
传感器 Java 数据库
探索Spring Boot的@Conditional注解的上下文配置
Spring Boot 的 `@Conditional` 注解可根据不同条件动态控制 Bean 的加载,提升应用的灵活性与可配置性。本文深入解析其用法与优势,并结合实例展示如何通过自定义条件类实现环境适配的智能配置。
478 0
探索Spring Boot的@Conditional注解的上下文配置
|
9月前
|
智能设计 Java 测试技术
Spring中最大化@Lazy注解,实现资源高效利用
本文深入探讨了 Spring 框架中的 `@Lazy` 注解,介绍了其在资源管理和性能优化中的作用。通过延迟初始化 Bean,`@Lazy` 可显著提升应用启动速度,合理利用系统资源,并增强对 Bean 生命周期的控制。文章还分析了 `@Lazy` 的工作机制、使用场景、最佳实践以及常见陷阱与解决方案,帮助开发者更高效地构建可扩展、高性能的 Spring 应用程序。
352 0
Spring中最大化@Lazy注解,实现资源高效利用

热门文章

最新文章