有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Spring配置初始化方法

我怎样才能让Spring运行init方法呢?我需要获取代理异步类,并用它进行一些初始化

@Configuration
@EnableAsync
public class Config  {

 @Bean
 public AsyncBean asyncProxyBean(){
    return new AsyncBean();
 }

 public void init(){
   doStuffWithProxy(asyncProxyBean());
 }

 @Bean
 public String thisIsHack(){ //this runs the init code but bean is a bit hacky
    doStuffWithProxy(asyncProxyBean());
    return "";
 }

}

共 (3) 个答案

  1. # 2 楼答案

    • 通常你可以对原始对象做一些事情。您很少需要使用代理做事情——这样您就依赖于一些spring内部(它使用动态代理的方式)
    • 如果你真的需要代理,那么我想你可以尝试使用BeanPostProcessor
  2. # 3 楼答案

    使用@PostConstruct注释以及:

    • <context:annotation-config />
    • <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />

    详见here。这是一个JavaEE注释,因此可能不适合您的环境