構造函數->PostConstruct->InitializingBean的afterPropertiesSet方法->XML中bean的init-method指定初始化方法
在使用PostConstruct是忽略了Spring對Bean的注入是通過掃描包中類的注解實作的,沒有在XML中配置相關資訊
(<context:component-scan base-package="com.sxd.bean"></context:component-scan>)
,
導緻PostConstruct指定的方法沒有執行
public class User implements InitializingBean {
public User() {
System.out.println("User() Construct.");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("AfterPropertiesSet.");
}
@PostConstruct
public void init() {
System.out.println("PostConstruct Init.");
}
public void init_method() {
System.out.println("Init method.");
}
}
XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<!-- Definition for textEditor bean -->
<bean id="user" class="com.sxd.bean.User" autowire="byType" init-method="init_method"></bean>
<context:component-scan base-package="com.sxd.bean"></context:component-scan>
<context:annotation-config></context:annotation-config>
</beans>
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiAzNvwVZ2x2bzNXak9CX90TQNNkRrFlQKBTSvwFbslmZvwFMwQzLcVmepNHdu9mZvwFVywUNMZTY18CX052bm9CX9MmeOpXRq50dNpXTmZEWjZXUYpVd1kmYr50MZV3YyI2cKJDT29GRjBjUIF2LcRHelR3LcJzLctmch1mclRXY39TO2UzM1cDMwIDNxIDM4EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)