spring @postConstruct init-method constructor和afterSetProperties() 执行顺序

来源:互联网 发布:windows文件系统书籍 编辑:程序博客网 时间:2024/06/07 08:49

示例代码:

package com.spring.initbean;import javax.annotation.PostConstruct;import org.springframework.beans.factory.InitializingBean;import org.springframework.stereotype.Component;/** * created by anyanwen on 2017/7/20. */public class InitSequenceBean implements InitializingBean {    private boolean properties;    public InitSequenceBean() {        System.out.println("InitSequenceBean constructor");    }    public void setProperties(boolean properties) {        System.out.println("InitSequenceBean set properties");        this.properties = properties;    }    @Override    public void afterPropertiesSet() throws Exception {        System.out.println("InitSequenceBean afterPropertiesSet");    }    @PostConstruct    public void postConstruct() {        System.out.println("InitSequenceBean postConstruct");    }    public void initMethod() {        System.out.println("InitSequenceBean initMethod");    }    public boolean isProperties() {        return properties;    }    public static void main(String[] args) {    }}

spring配置文件

<?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"       xmlns:cache="http://www.springframework.org/schema/cache" xmlns:aop="http://www.springframework.org/schema/aop"       xmlns:crane="http://code.dianping.com/schema/crane"       xsi:schemaLocation="http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd           http://www.springframework.org/schema/beans           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd           http://www.springframework.org/schema/context           http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">    <context:annotation-config/>    <context:component-scan base-package="com"/>    <bean id="initSequenceBean" class="com.spring.initbean.InitSequenceBean"        init-method="initMethod">        <property name="properties" value="true"></property>    </bean></import></beans>

测试类

package com.spring.initbean;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;/** * created by anyanwen on 2017/7/20. */public class InitSequenceBeanTest {    @Test    public void test() {        ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-config.xml");    }}

输出:

InitSequenceBean constructor
InitSequenceBean set properties
InitSequenceBean postConstruct
InitSequenceBean afterPropertiesSet
InitSequenceBean initMethod

阅读全文
0 0
原创粉丝点击