java Spring:@PostConstruct 没有被调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13918988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 14:26:30  来源:igfitidea点击:

Spring: @PostConstruct is not called

javaspring

提问by Alan Evangelista

Class A:

A类:

package myproject.web.factory.components;

@Component
public class AppComponentFactory{
}

Class B

B级

package myproject.web.components;
import myproject.web.factory.components.AppComponentFactory;

@Component
public class AdminTabSheet{

   @Autowired
   private AppComponentFactory appComponentFactory;

   public AdminTabSheet() {
   }

   @PostConstruct
   public void init() {
      // does something with appComponentFactory
   }
}

Configuration XML:

配置 XML:

<context:component-scan base-package="myproject.spring" />

WebConfig.java:

WebConfig.java:

package myproject.spring.config;

@Configuration
@ComponentScan(basePackages = { "myproject.web.components"})
public class WebConfig {

I have followed all the rules in http://docs.oracle.com/javaee/5/api/javax/annotation/PostConstruct.html:

我遵循了http://docs.oracle.com/javaee/5/api/javax/annotation/PostConstruct.html 中的所有规则:

  • Only one method can be annotated with this annotation.
  • The method MUST NOT have any parameters except in the case of EJB interceptors
  • The return type of the method MUST be void.
  • The method MUST NOT throw a checked exception.
  • The method on which PostConstruct is applied MAY be public, protected, package private or private.
  • The method MUST NOT be static .
  • 这个注解只能注解一种方法。
  • 除 EJB 拦截器外,该方法不得有任何参数
  • 方法的返回类型必须是 void。
  • 该方法不得抛出已检查的异常。
  • 应用 PostConstruct 的方法可以是 public、protected、package private 或 private。
  • 该方法不能是静态的。

Any ideas?

有任何想法吗?

回答by bleidi

If there was no typo, I believe the correct would be

如果没有错别字,我相信正确的应该是

@ComponentScan(basePackages = { "myproject.web"})

since AppComponentFactoryis in myproject.web.factorypackage.

因为AppComponentFactorymyproject.web.factory包里。