2011-11-09 72 views
9

我使用下面的春季3.1配置:春3.1配置:环境不注射

@Configuration 
@EnableTransactionManagement 
public class DataConfig { 
    @Inject 
    private Environment env; 
    @Inject 
    private DataSource dataSource; 

    // @Bean 
    public SpringLiquibase liquibase() { 
     SpringLiquibase b = new SpringLiquibase(); 
     b.setDataSource(dataSource); 
     b.setChangeLog("classpath:META-INF/db-changelog-master.xml"); 
     b.setContexts("test, production"); 
     return b; 
    } 

    @Bean 
    public EntityManagerFactory entityManagerFactory() { 
     LocalContainerEntityManagerFactoryBean b = new LocalContainerEntityManagerFactoryBean(); 
     b.setDataSource(dataSource); 
     HibernateJpaVendorAdapter h = new HibernateJpaVendorAdapter(); 
     h.setShowSql(env.getProperty("jpa.showSql", Boolean.class)); 
     h.setDatabasePlatform(env.getProperty("jpa.database")); 

     b.setJpaVendorAdapter(h); 
     return (EntityManagerFactory) b; 
    } 

    @Bean 
    public PersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor() { 
     PersistenceExceptionTranslationPostProcessor b = new PersistenceExceptionTranslationPostProcessor(); 
     // b.setRepositoryAnnotationType(Service.class); 
     // do this to make the persistence bean post processor pick up our @Service class. Normally 
     // it only picks up @Repository 
     return b; 

    } 

    @Bean 
    public PlatformTransactionManager transactionManager() { 
     JpaTransactionManager b = new JpaTransactionManager(); 
     b.setEntityManagerFactory(entityManagerFactory()); 
     return b; 
    } 

    /** 
    * Allows repositories to access RDBMS data using the JDBC API. 
    */ 
    @Bean 
    public JdbcTemplate jdbcTemplate() { 
     return new JdbcTemplate(dataSource); 
    } 


    @Bean(destroyMethod = "close") 
    public DataSource dataSource() { 

     BasicDataSource db = new BasicDataSource(); 
     if (env != null) { 
      db.setDriverClassName(env.getProperty("jdbc.driverClassName")); 
      db.setUsername(env.getProperty("jdbc.username")); 
      db.setPassword(env.getProperty("jdbc.password")); 
     } else { 
      throw new RuntimeException("environment not injected"); 
     } 
     return db; 
    } 
} 

的问题是,可变env没有注入和始终为空。

我还没有做过关于环境设置的任何内容,因为我不知道它是否需要或如何使用。我看着温室的例子,我没有找到任何专门针对环境的东西。我应该怎么做才能确保env被注入?

的相关文件:

// CoreConfig.java 
@Configuration 
public class CoreConfig { 

    @Bean 
    LocalValidatorFactoryBean validator() { 
     return new LocalValidatorFactoryBean(); 
    } 

    /** 
    * Properties to support the 'standard' mode of operation. 
    */ 
    @Configuration 
    @Profile("standard") 
    @PropertySource("classpath:META-INF/runtime.properties") 
    static class Standard { 
    } 

} 


// the Webconfig.java 
@Configuration 
@EnableWebMvc 
@EnableAsync 
// @EnableScheduling 
@EnableLoadTimeWeaving 
@ComponentScan(basePackages = "com.jfd", excludeFilters = { @Filter(Configuration.class) }) 
@Import({ CoreConfig.class, DataConfig.class, SecurityConfig.class }) 
@ImportResource({ "/WEB-INF/spring/applicationContext.xml" }) 
public class WebConfig extends WebMvcConfigurerAdapter { 


    @Override 
    public void addResourceHandlers(ResourceHandlerRegistry registry) { 
     registry.addResourceHandler("/images/**").addResourceLocations(
       "/images/"); 
    } 

    @Bean 
    public BeanNameViewResolver beanNameViewResolver() { 
     BeanNameViewResolver b = new BeanNameViewResolver(); 
     b.setOrder(1); 
     return b; 
    } 

    @Bean 
    public InternalResourceViewResolver internalResourceViewResolver() { 
     InternalResourceViewResolver b = new InternalResourceViewResolver(); 
     b.setSuffix(".jsp"); 
     b.setPrefix("/WEB-INF/jsp/"); 
     b.setOrder(2); 
     return b; 
    } 

    @Bean 
    public CookieLocaleResolver localeResolver() { 
     CookieLocaleResolver b = new CookieLocaleResolver(); 
     b.setCookieMaxAge(100000); 
     b.setCookieName("cl"); 
     return b; 
    } 

    // for messages 
    @Bean 
    public ResourceBundleMessageSource messageSource() { 
     ResourceBundleMessageSource b = new ResourceBundleMessageSource(); 
     b.setBasenames(new String[] { "com/jfd/core/CoreMessageResources", 
       "com/jfd/common/CommonMessageResources", 
       "com/jfd/app/AppMessageResources", 
       "com/jfd/app/HelpMessageResources" }); 
     b.setUseCodeAsDefaultMessage(false); 
     return b; 
    } 

    @Bean 
    public SimpleMappingExceptionResolver simpleMappingExceptionResolver() { 
     SimpleMappingExceptionResolver b = new SimpleMappingExceptionResolver(); 

     Properties mappings = new Properties(); 
     mappings.put("org.springframework.web.servlet.PageNotFound", "p404"); 
     mappings.put("org.springframework.dao.DataAccessException", 
       "dataAccessFailure"); 
     mappings.put("org.springframework.transaction.TransactionException", 
       "dataAccessFailure"); 
     b.setExceptionMappings(mappings); 
     return b; 
    } 

    /** 
    * ViewResolver configuration required to work with Tiles2-based views. 
    */ 
    @Bean 
    public ViewResolver viewResolver() { 
     UrlBasedViewResolver viewResolver = new UrlBasedViewResolver(); 
     viewResolver.setViewClass(TilesView.class); 
     return viewResolver; 
    } 

    /** 
    * Supports FileUploads. 
    */ 
    @Bean 
    public MultipartResolver multipartResolver() { 
     CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); 
     multipartResolver.setMaxUploadSize(500000); 
     return multipartResolver; 
    } 

    // for configuration 
    @Bean 
    public CompositeConfigurationFactoryBean myconfigurations() 
      throws ConfigurationException { 
     CompositeConfigurationFactoryBean b = new CompositeConfigurationFactoryBean(); 
     PropertiesConfiguration p = new PropertiesConfiguration(
       "classpath:META-INF/app-config.properties"); 
     p.setReloadingStrategy(new FileChangedReloadingStrategy()); 

     b.setConfigurations(new org.apache.commons.configuration.Configuration[] { p }); 
     b.setLocations(new ClassPathResource[] { new ClassPathResource(
       "META-INF/default-config.properties") }); 
     return b; 
    } 

    @Bean 
    org.apache.commons.configuration.Configuration configuration() 
      throws ConfigurationException { 
     return myconfigurations().getConfiguration(); 
    } 


// and the SecurityConfig.java 
@Configuration 
@ImportResource({ "/WEB-INF/spring/applicationContext-security.xml" }) 
public class SecurityConfig { 

    @Bean 
    public BouncyCastleProvider bcProvider() { 
     return new BouncyCastleProvider(); 
    } 

    @Bean 
    public PasswordEncryptor jasyptPasswordEncryptor() { 

     ConfigurablePasswordEncryptor b = new ConfigurablePasswordEncryptor(); 
     b.setAlgorithm("xxxxxx"); 
     return b; 
    } 

    @Bean 
    public PasswordEncoder passwordEncoder() { 
     PasswordEncoder b = new org.jasypt.spring.security3.PasswordEncoder(); 
     b.setPasswordEncryptor(jasyptPasswordEncryptor()); 
     return b; 
    } 

} 
在applicationContext.xml

,它仅进口2个XML来配置缓存和卡桑德拉,所以它可能不会是非常重要的。

+0

您使用的是Java EE兼容服务器吗? – maks

回答

1

如果您不使用完整的Java EE兼容服务器,则必须将javax.inject.jar添加到项目类路径中,以添加对@Inject的支持。您也可以尝试使用spring的本地@Autowired注释。

+0

谢谢,Maks,inject.jar在那里。这个项目使用xml配置和注解驱动工作正常。我想看看它如何与3.1并且不能通过这个障碍。一定是想念我无法弄清楚的事情。 – jfd

+0

嗯,我试图在Spring 3.1上使用@inject和Environment,它工作正常。请显示你的xml配置,如果可能的话 – maks

+0

你好,麦克斯,我在那里更新了更多文件的原文。我不知道如何在这里添加东西。谢谢 – jfd

1

@jfd,

我没有立即看到什么不对您的配置会导致失败注入环境。

如果您从头开始使用空的@Configuration类,然后@Inject环境,它是否适合您?

如果是,那么它在什么时候开始失败?

您是否愿意将该示例缩减到可能失败的最小配置并将其作为复制项目提交?这里的说明使这尽可能简单:https://github.com/SpringSource/spring-framework-issues#readme

谢谢!

+0

谢谢克里斯。当我剥去一切并逐渐将它们添加回来。我发现secrityConfig.java是导致问题的原因。仍然试图找出原因。但后来我坚持另一个问题,休眠抱怨“Dialect类未找到:MYSQL”,这是一个非XML问题。所以我猜电动势/交易部分仍然不正确 – jfd

+0

这太微妙了。我发现如果有一个或所有的postConstruct,我需要在属性之后调用所有的属性。真的吗?我得到的另一件事是一些配置文件加载,一些永远不会然后他们扫描包,所以不autofire不工作,因为一些配置文件从未调用。 – jfd

+0

你好克里斯,我认为这个问题可能与我发现的春季安全有关。 – jfd

2

问题在于记住我功能的弹簧安全。如果我拿这条线<code> <remember-me data-source-ref="dataSource" /> </code>出来。一切正常。如果这一行出现,它会尝试在其他任何事情之前加载数据库,并且env从未被注入。

1

我已经为here提及我的项目检测到类似的错误。 我也弄清楚,调用afterproperties是获取sessionFactory所必需的。 ...是的,我也使用Spring Security(这可能是问题的根源)。

我的@Configuration注释类使用@ComponentScan包含包含基于Hibernate的DAO的包和一个用于创建DAO使用的SessionFactory的@Bean注解方法。在运行时,抛出异常,提到没有找到'sessionFactory'或'hibernateTemplate'。看起来DAO是在SessionFactory创建之前构建的。对我来说一个解决方法是将组件扫描指令放回到XML文件()中,并用该文件的@ImportResource替换@ComponentScan。另一个有趣的事实是:如果包含@ComponentScan,则在方法sessionFactory()中设置的断点永远不会到达!

+0

我通过将配置文件仅用于扫描并加载最后一个(使用@Import(xxx.class))来传递该问题。移动到java配置时需要注意很多:1)afterproperty或postconstruct函数调用; 2)除字符串以外的枚举和类路径资源; 3)旧物业方式以外的环境物品等等,有些物品应该像春天的物业一样在春季机械中处理。 – jfd

1

我也有类似的问题与春季社会示例应用程序。

我将字段级别@Inject转换为构造函数级别之后注入它的工作。

5

不知道为什么,但使用@Resource注释为我工作。 @Autowired总是返回null。