【问题标题】:Initializing Spring in not-web annotation-configured application在非 web 注释配置的应用程序中初始化 Spring
【发布时间】:2014-01-11 16:31:25
【问题描述】:

我的 java 应用程序使用 Spring 原型注解(@Controller、@Component)和自动装配注解来管理依赖注入。

它不是 web 应用程序,只是普通的 jar。它也是基于纯注释的代码,即根本没有 xml。

仅从 main 方法初始化基于 Spring 注解的应用程序上下文和默认配置的正确方法是什么?

【问题讨论】:

标签: spring annotations applicationcontext


【解决方案1】:

使用@Configuration 命名一个AppConfig,相当于applicationContext.xml。

@Configuration
public class AppConfig {

  @Bean(initMethod = "init")
  public Foo foo() {
      return new Foo();
  }

  @Bean(destroyMethod = "cleanup")
  public Bar bar() {
      return new Bar();
  }
}

并在 main 方法中新建一个 AnnotationConfigApplicationContext。

public static void main(String[] args) {
  ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
  Foo foo = ctx.getBean(Foo.class);
  //etc
}

【讨论】:

  • 使用 @ComponentScan("com.company") 注释回答问题
猜你喜欢
  • 1970-01-01
  • 2012-05-03
  • 1970-01-01
  • 2013-06-16
  • 1970-01-01
  • 2017-01-10
  • 2011-01-23
  • 2011-03-16
  • 2015-03-06
相关资源
最近更新 更多