gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:56:23 24 4
gpt4 key购买 nike

为什么不将 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()");
}
}

下面是我的 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>

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

最佳答案

在 Spring 环境初始化回调方法(由 @PostConstruct 注释的方法)仅在 spring-managed-beans 上有意义。制作您的 PropertyLoader 的实例类托管,您必须执行以下操作之一:

  • 在上下文配置中显式注册您的类(就像您所做的那样)<bean id="proeprtyLoader" class="org.stalwartz.config.PropertyLoader"></bean>
  • 让组件扫描完成工作(就像您几乎所做的那样),但类必须由 @Component, @Repository, @Service, @Controller 之一注释。 .

  • 来自 Spring documentation 的注释: 使用 <context:component-scan>隐式启用 <context:annotation-config> 的功能.通常不需要包含 <context:annotation-config>使用 <context:component-scan> 时的元素.

    关于spring - @PostConstruct spring 在没有 bean 声明的情况下不会被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36287332/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com