Spring 3.1 Java配置 - @ Autowired,@ Configuration和@Profile挑战

时间:2011-09-01 14:27:30

标签: spring spring-mvc

我正在使用Spring 3.1和Servlet 3.0,并且对新的Java配置选项以及使用Spring配置文件非常感兴趣并且遇到了挑战。尽管我在网上看到的所有例子都让它看起来像是一个用@Configuration注释的类,但是其他对象@Autowired到它们中我所看到的是自动装配直到几个bean之后才会发生已生成@Configuration类。

这是我的初始化程序:

public class SpringMvcInitializer implements WebApplicationInitializer {

private static org.apache.log4j.Logger log= Logger.getLogger(SpringMvcInitializer.class);

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    // Create the 'root' Spring application context
    AnnotationConfigWebApplicationContext rootContext  = new AnnotationConfigWebApplicationContext();
    rootContext.scan("org.jc.config");
    servletContext.addListener(new ContextLoaderListener(rootContext));

    // Secures the application
    servletContext.addFilter("securityFilter", new DelegatingFilterProxy("springSecurityFilterChain"))
        .addMappingForUrlPatterns(null, false, "/*");       

    ServletRegistration.Dynamic appServlet =
            servletContext.addServlet("appServlet", new DispatcherServlet(new GenericWebApplicationContext()));
    appServlet.setLoadOnStartup(1); 

    appServlet.addMapping("/");

    log.info("Mvc Initializer starting");
}

我的网站配置

@Configuration
@EnableWebMvc
@ComponentScan(basePackages="org.jc" )
public class WebConfig extends WebMvcConfigurerAdapter {

@Bean
public InternalResourceViewResolver configureInternalResourceViewResolver() {
    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setPrefix("/WEB-INF/");
    resolver.setSuffix(".jsp");
    return resolver;
}

@Override
public void configureResourceHandling(ResourceConfigurer configurer) {
    configurer.addPathMapping("/resources/**");
    configurer.addResourceLocation("/resources/");
}

我的JPA配置类

@Configuration
public class JpaConfig {
private static Logger logger = Logger.getLogger(JpaConfig.class);

private AppEnvironmentI appEnvironment;

@Autowired
public void setAppEnvironment(AppEnvironmentI appEnvironment) {
    this.appEnvironment = appEnvironment;
    checkAppEnv("setAppEnvironment");
}

@Bean
public AppUser globalUser(){
    checkAppEnv("globalUser entry");
    AppUser appUser = new AppUser();
    checkAppEnv("globalUser exit");
    return appUser;
}

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(){
    checkAppEnv("entityManagerFactory entry");
    LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean ();
    emf.setDataSource(dataSource());
    emf.setJpaVendorAdapter(this.jpaAdapter());
    emf.setPersistenceUnitName("JcEntities2");
    checkAppEnv("entityManagerFactory exit");
    return emf;
}

@Bean
public DataSource dataSource(){
    checkAppEnv("dataSource entry");
    DriverManagerDataSource ds = new DriverManagerDataSource();
    ds.setDriverClassName("org.apache.derby.jdbc.EmbeddedDriver");
    ds.setUrl("jdbc:derby://localhost:1527/JcTestDb");
    ds.setUsername("jc");
    ds.setPassword("pwd");
    checkAppEnv("dataSource exit");
    return ds;
}

@Bean
public JpaVendorAdapter jpaAdapter() {
    checkAppEnv("jpaAdapter entry");
    HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
    hibernateJpaVendorAdapter.setShowSql(true);
    hibernateJpaVendorAdapter.setDatabase(Database.DERBY);
    checkAppEnv("jpaAdapter exit");
    return hibernateJpaVendorAdapter;
}

@Bean
public PlatformTransactionManager transactionManager() {
    checkAppEnv("transactionManager entry and exit");
    return new JpaTransactionManager( entityManagerFactory().getObject() );
}

private void checkAppEnv(String _method){
    if(this.appEnvironment == null){
        logger.info(_method + " - App Environment is null!!!!");
    }else{
        logger.info(_method + " - App Environment JpaConfig = " + appEnvironment.externalPropertiesFile().getPropertyValue("environment"));
    }
}

我的个人资料类

@Configuration
@Profile("local")
public class AppEnvironmentLocal implements AppEnvironmentI{
private static Logger logger = Logger.getLogger(AppEnvironmentLocal.class);

@Bean
public AppEnvironment externalPropertiesFile(){
    logger.info("Fetching properties file for LOCAL environment");
    Properties props = FileUtilsJc.getPropertiesFromFlatFile("C:\\AppConf\\JcConf\\JcConfLocal.properties");
    AppEnvironment exf = new AppEnvironment(props);
    return exf;
}
}

Logger输出:看起来Spring 3.1在AppEnvironment注入类之前首先尝试创建Entity Manager Factory bean。因此它创建了除全局用户(我用于测试的虚拟bean)和事务管理器之外的所有bean,注入AppEnvironment,然后创建全局用户和事务管理器bean。

任何想法都非常感谢!

01-Sep-2011 10:20:55  INFO Mvc Initializer starting
01-Sep-2011 10:20:55  INFO entityManagerFactory entry - App Environment is null!!!!
01-Sep-2011 10:20:55  INFO dataSource entry - App Environment is null!!!!
01-Sep-2011 10:20:55  INFO dataSource exit - App Environment is null!!!!
01-Sep-2011 10:20:55  INFO jpaAdapter entry - App Environment is null!!!!
01-Sep-2011 10:20:55  INFO jpaAdapter exit - App Environment is null!!!!
01-Sep-2011 10:20:55  INFO entityManagerFactory exit - App Environment is null!!!!
01-Sep-2011 10:20:55  INFO Fetching properties file for LOCAL environment
01-Sep-2011 10:20:55  INFO setAppEnvironment - App Environment JpaConfig = LOCAL

以下是我用来连接它的示例代码的URL:

http://blog.springsource.com/2011/02/14/spring-3-1-m1-introducing-profile/

我发现文档声明在Spring 3.1之前有必要将@AnnotationDrivenConfig注释添加到您的注入类中,以便@Autowired工作但是在Spring 3.1中已经弃用了我发现了一堆帖子正在寻找这个注释但是注入Configuration对象时没有解决任何问题!

1 个答案:

答案 0 :(得分:2)

据我了解,@Configuration bean是在非配置bean之前构建的,用@Bean标记的方法会生成尚未 bean的对象返回;否则构造bean的顺序是未定义的(除了一些特殊的bean类型;标准属性文件加载器很早就被调用,因此它们发现的值可用于设置@Configuration bean)。直接调用bean方法是不受欢迎的;让Spring为你做,因为它会在 @Bean方法返回后连接属性