【问题标题】:@Autowired issue with @Configurable servlet@Configurable servlet 的 @Autowired 问题
【发布时间】:2012-10-05 10:13:27
【问题描述】:

我正在尝试通过以下方式将类自动装配到 WebSocketServlet 中:

@Configurable(autowire=Autowire.BY_TYPE)
public class MyServlet extends WebSocketServlet {
    @Autowired
    public MyClass field;

    // etc...
}

这是我的配置:

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

<bean id="config" class="org.*.MyClass">
   <!-- a bunch of properties -->
</bean>

请注意,只要我在 Spring @Controller,autowire 就可以正常工作。我不得不退出,因为我不知道如何将 WebSocketsServlet 映射到 @Controller 的方法,就像使用常规 servlet 一样。

知道我可能缺少什么吗?

【问题讨论】:

  • @Configurable 需要 AspectJ 加载时间或编译时间编织才能工作,它不能单独与 Spring AOP 一起工作。您能否确认您已启用 Aspectj 并启用了加载/编译时编织

标签: java spring autowired configurable eclipse-virgo


【解决方案1】:

为了使用@Configurable,您需要在游览上下文中包含这些行:

<context:load-time-weaver aspectj-weaving="true"/>
<context:spring-configured/>    
<context:annotation-config />
<context:component-scan base-package="org.*" />

另外,我认为你必须在 Manifest 的 Import-Library 部分引用 spring-aspect。

我没有成功使它工作,在 Eclipse 的 Virgo 论坛上有一个帖子。 如果你成功了,请告诉我如何;)

【讨论】:

  • 在下面检查我的答案 - 我不得不放弃 @Configurable 并使用 SpringBeanAutowiringSupport 东西:)
【解决方案2】:

摆脱 @Configurable 并在 servlet init 方法中执行以下操作即可:

@Override
public void init() throws ServletException {
   super.init();
   SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}

【讨论】:

    【解决方案3】:

    根据spring documentation

    可以通过使用@Autowired@Inject 注释将Spring 环境注入@Configuration 类来查找外部化值:

     @Configuration
     public class AppConfig {
         @Inject Environment env;
    
         @Bean
         public MyBean myBean() {
             MyBean myBean = new MyBean();
             myBean.setName(env.getProperty("bean.name"));
             return myBean;
         }
     }
    

    【讨论】:

      猜你喜欢
      • 2022-11-08
      • 2011-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-14
      • 2013-02-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多