【问题标题】:Spring DI based on annotations基于注解的 Spring DI
【发布时间】:2015-04-09 19:47:36
【问题描述】:

我尝试使用弹簧,并坚持使用弹簧配置。正如您在标题中看到的,我尝试配置注释并尝试使用 spring-boot(我认为这非常好)。

所以我的问题很简单(我认为),就是如何将我的 bean 注入到 servlet(其他类等)

1) 我有一个已配置的应用程序

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(applicationClass, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(applicationClass);
    }

    private static Class<Application> applicationClass = Application.class;

    @Bean(name = "some", autowire = Autowire.BY_TYPE)
    @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
    public Some someInit() {
        return new Some();
    }
}

2) 豆子

public class Some {

    public Some() {}

    public Integer get() {
        return 1;
    }
}

3) 和我尝试注入 bean 的 servlet

public class IndexServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public IndexServlet() {
        super();
    }

    @Autowired
    Some some;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer integer = some.get();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }

}

所以,有些总是空的,我不明白为什么。我试图调试代码,我看到 Application 已初始化,并且 Some in Application 已实例化。但它没有注入到我的 servlet。

谢谢!

【问题讨论】:

    标签: java spring servlets dependency-injection spring-annotations


    【解决方案1】:

    好吧,我找到了解决方案,把下面的代码放在你的 Servlet 中

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
                config.getServletContext());
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-15
      • 2015-06-25
      • 1970-01-01
      • 2016-05-04
      • 1970-01-01
      • 2014-09-02
      • 2015-05-14
      • 1970-01-01
      相关资源
      最近更新 更多