博客
关于我
Spring笔记(2) - 生命周期/属性赋值/自动装配及部分源码解析
阅读量:422 次
发布时间:2019-03-06

本文共 3849 字,大约阅读时间需要 12 分钟。

Spring Framework开发指南:从基础到进阶

一、Bean的生命周期

1. 自定义初始化与销毁方法

Spring允许开发者自定义Bean的初始化和销毁逻辑,主要有以下几种实现方式:

XML方式:

@Bean方式:

@Bean(initMethod = "", destroyMethod = "")public Person person() {    System.out.println("注入容器。。。。。");    return new Person("张三", 20);}

接口实现方式:

@Componentpublic class Person implements InitializingBean, DisposableBean {    public Person() {        System.out.println("Person 。。。 constructor");    }    @Override    public void afterPropertiesSet() throws Exception {        System.out.println("Person 。。。afterPropertiesSet");    }    @Override    public void destroy() throws DestroyFailedException {        System.out.println("Person 。。。destroy");    }}

2. @PostConstruct和@PreDestroy

JSR-250规范提供了@PostConstruct和@PreDestroy注解,用于在Bean的生命周期中执行初始化和销毁逻辑:

@Componentpublic class Color {    public Color() {        System.out.println("Color 。。。 constructor");    }    @PostConstruct    public void init() throws Exception {        System.out.println("Color 。。。init");    }    @PreDestroy    public void destroy() {        System.out.println("Color 。。。destroy");    }}

3. BeanPostProcessor扩展

BeanPostProcessor接口允许开发者在Bean的初始化和销毁过程中添加自定义逻辑。以下是一个实现示例:

@Componentpublic class MyBeanPostProcessor implements BeanPostProcessor {    @Override    public Object postProcessBeforeInitialization(Object bean, String beanName) {        System.out.println("postProcessBeforeInitialization====》【" + bean + "】:" + beanName);        return bean;    }    @Override    public Object postProcessAfterInitialization(Object bean, String beanName) {        System.out.println("postProcessAfterInitialization====》【" + bean + "】:" + beanName);        return bean;    }}

4. 内部原理

从Spring的doCreateBean方法可以看出,Bean的初始化过程包括以下几个关键步骤:

  • populateBean:对Bean的属性进行赋值
  • initializeBean:调用applyBeanPostProcessorsBeforeInitialization和applyBeanPostProcessorsAfterInitialization,执行BeanPostProcessor的逻辑
  • 调用初始化方法
  • 调用销毁方法
  • 二、属性赋值

    1. @Value注解

    @Value注解用于注入基本类型值或SpEL表达式:

    public class Person {    @Value("张三")    private String name;    @Value("#{20-1}")    private Integer age;}

    2. @PropertySource注解

    @PropertySource用于读取外部配置文件:

    public class Person {    @Value("张三")    private String name;    @Value("#{20-1}")    private Integer age;    @Value("${sex}")    private String sex;}@propertysource(value = "classpath:/global.properties")public class BeanConfig {}

    三、自动装配

    1. Spring定义注解

    @Autowired/@Qualifier/@Primary

    @Servicepublic class UserService {    @Qualifier("userDao")    @Autowired    private UserDao userDao;    public void printf() {        System.out.println(userDao);    }}

    @Resource/@Inject(Java规范)

    public class UserService {    @Resource(name = "userDao")    private UserDao userDao;}

    2. Aware注入

    Spring提供了一些Aware接口,用于注入Spring底层组件:

    public class Color implements ApplicationContextAware {    private ApplicationContext applicationContext;    @Override    public void setApplicationContext(ApplicationContext applicationContext) {        this.applicationContext = applicationContext;    }}

    3. 环境配置

    @Profile注解用于指定Bean在特定环境下注册:

    @PropertySource("classpath:/db.properties")@Configurationpublic class BeanProfileConfig {    @Value("${db.user}")    private String user;    @Value("${db.driverClass}")    private String driverClass;    @Profile("test")    @Bean    public DataSource testDataSource(@Value("${db.password}") String pwd) {        //数据库配置...    }    @Profile("dev")    @Bean    public DataSource devDataSource(@Value("${db.password}") String pwd) {        //数据库配置...    }    @Profile("pro")    @Bean    public DataSource proDataSource(@Value("${db.password}") String pwd) {        //数据库配置...    }}

    四、使用示例

    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(BeanConfig.class);context.register(BeanProfileConfig.class);context.setEnvironment(new StandardEnvironment().addProperty("spring.profiles.active", "test"));context.refresh();

    转载地址:http://blluz.baihongyu.com/

    你可能感兴趣的文章
    Python 中的线程
    查看>>
    Python 中的继承机制是什么样的?
    查看>>
    Python 中的装饰器是什么?
    查看>>
    Python 中的装饰器是如何工作的,有哪些实际应用场景?
    查看>>
    python读excel
    查看>>
    Python 中读取 CSV 文件-ChatGPT4o作答
    查看>>
    python请求html_使用Python请求获取HTML?
    查看>>
    Python 之匿名函数和偏函数
    查看>>
    python 之栈的实现
    查看>>
    python语音播放
    查看>>
    python语言:装饰器原理
    查看>>
    Python 交互式数据可视化详解
    查看>>
    python语言有哪些优点和缺点_Python有哪些优缺点,你了解吗?
    查看>>
    Python 从入门到精通:30天速成教程到底有多狠?你能坚持下来吗?
    查看>>
    Python 从数据库中存储和检索密码的最安全方法
    查看>>
    Python语言及其应用 - 知识点遍历
    查看>>
    Python 优化提速的 8 个小技巧
    查看>>
    Python 余弦相似度与皮尔逊相关系数 计算
    查看>>
    python 使用execjs 报编码错误解决办法,UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0xac in position 145: il
    查看>>
    python 使用filetype校验文件
    查看>>