@PostConstruct spring 在没有 bean 声明的情况下不会被调用

Jig*_*aik 5 spring spring-mvc

为什么不将 bean 放入 applicationContext.xml 就不会调用 post 构造

这是我的类,其中包含 @PostConstruct 注释。

package org.stalwartz.config;

import javax.annotation.PostConstruct;
import javax.inject.Singleton;

@Singleton
public class PropertyLoader {

    @PostConstruct
    public void init() {
         System.out.println("PropertyLoader.init()");
    }
}
Run Code Online (Sandbox Code Playgroud)

下面是我的 applicationContext.xml

<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" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr" xmlns:tx="http://www.springframework.org/schema/tx"
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.xsd 
 http://www.springframework.org/schema/mvc 
 http://www.springframework.org/schema/mvc/spring-mvc.xsd 
 http://www.springframework.org/schema/tx 
 http://www.springframework.org/schema/tx/spring-tx.xsd 
 http://www.directwebremoting.org/schema/spring-dwr
 http://www.directwebremoting.org/schema/spring-dwr/spring-dwr-3.0.xsd">

<dwr:annotation-config />
<dwr:annotation-scan base-package="org.stalwartz" scanDataTransferObject="true" scanRemoteProxy="true" />
<dwr:url-mapping />

<!--  <bean id="proeprtyLoader" class="org.stalwartz.config.PropertyLoader"></bean>  -->

<dwr:controller id="dwrController" debug="false">
    <dwr:config-param name="activeReverseAjaxEnabled" value="true" />
</dwr:controller>

<context:annotation-config>
    <context:component-scan base-package="org.stalwartz" annotation-config="true"></context:component-scan>
</context:annotation-config>

<mvc:annotation-driven />
...
...
...
</beans>
Run Code Online (Sandbox Code Playgroud)

看起来很简单,但如果不取消注释 bean 声明,它就不起作用。

nuk*_*kie 1

Singleton 是一个范围注释。它可用于声明特定 bean 的“singletone”范围,但不能实例化它。请参阅这篇文章。

如果你想将你的类实例化为单例,你可以尝试 Spring Service注释。

@Service
public class PropertyLoader {

    @PostConstruct
    public void init() {
         System.out.println("PropertyLoader.init()");
    }
}
Run Code Online (Sandbox Code Playgroud)

另外,您可以用组件扫描替换注释配置标签。这是一篇 关于注释配置和组件扫描标签差异的好文章。