2011-11-09 29 views
9

Tôi đang sử dụng sau cho mùa xuân 3.1 cấu hình:Xuân 3.1 cấu hình: môi trường không được tiêm

@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; 
    } 
} 

vấn đề là biến env không tiêm và luôn luôn là null.

Tôi đã không làm bất cứ điều gì về việc thiết lập môi trường kể từ khi tôi không biết nếu nó cần thiết hoặc làm thế nào để. Tôi nhìn vào ví dụ nhà kính và tôi không tìm thấy bất cứ điều gì đặc biệt cho Môi trường. Tôi nên làm gì để đảm bảo rằng env được tiêm?

Các tập tin liên quan:

// 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; 
    } 

} 

trong applicationcontext.xml, nó chỉ nhập khẩu hai XMLs để bộ nhớ cache config và cassandra, vì vậy nó có thể không quan trọng.

+0

Bạn có đang sử dụng máy chủ tương thích Java EE không? – maks

Trả lời

1

Nếu bạn không sử dụng máy chủ tương thích Java EE đầy đủ, bạn phải bao gồm javax.inject.jar vào đường dẫn lớp dự án của bạn để thêm hỗ trợ của @Inject. Bạn cũng có thể thử sử dụng chú thích gốc @Autowired của mùa xuân.

+0

Cảm ơn, Maks, inject.jar là có. Dự án này đang sử dụng cấu hình xml và chú thích hướng hoạt động tốt. tôi đang cố gắng xem nó như thế nào với 3.1 và không thể vượt qua rào cản này. Nó phải được bỏ lỡ một cái gì đó mà tôi không thể tìm ra. – jfd

+0

Hmm, tôi đã cố gắng sử dụng @inject with Environment vào mùa xuân 3.1 và nó hoạt động tốt. Xin vui lòng, hiển thị cấu hình xml của bạn nếu nó có thể – maks

+0

Xin chào, Maks, tôi cập nhật bản gốc với nhiều tập tin ở đó. tôi không biết làm thế nào để thêm điều xuống đây. cảm ơn – jfd

1

@jfd,

Tôi không ngay lập tức nhìn thấy bất cứ điều gì sai trái với cấu hình của bạn có thể gây ra một sự thất bại để tiêm Môi trường.

Nếu bạn bắt đầu từ đầu với một lớp @Configuration trống rỗng, và sau đó @Inject Môi trường, nó làm việc cho bạn?

Nếu có, thì ở mức độ nào thì nó bắt đầu thất bại?

Bạn có sẵn sàng để giảm ví dụ xuống cấu hình nhỏ nhất có thể thất bại và gửi nó như một dự án sinh sản? Hướng dẫn tại đây thực hiện điều này đơn giản càng tốt: https://github.com/SpringSource/spring-framework-issues#readme

Cảm ơn!

+0

cảm ơn Chris. khi tôi vứt bỏ mọi thứ và dần dần thêm chúng trở lại. Tôi thấy rằng secrityConfig.java là một trong những nguyên nhân gây ra vấn đề. Vẫn cố gắng tìm ra lý do tại sao. nhưng sau đó tôi bị mắc kẹt trên một vấn đề khác mà hibernate phàn nàn "lớp Dialect không tìm thấy: MYSQL" mà không phải là một vấn đề trong xml. vì vậy tôi đoán phần emf/giao dịch vẫn không chính xác – jfd

+0

Điều này quá tinh tế. Tôi thấy tôi cần phải gọi tất cả các tài sản sau nếu có, hoặc tất cả các postConstruct. điều đó có đúng không? một điều tôi nhận được là một số tập tin cấu hình được nạp và một số không bao giờ sau đó họ quét gói để không autowire không làm việc kể từ khi một số tập tin cấu hình không bao giờ được gọi. – jfd

+0

Xin chào Chris, tôi nghĩ vấn đề có thể xảy ra với bảo mật mùa xuân khi tôi phát hiện ra. – jfd

2

Sự cố xảy ra với tính năng bảo mật mùa xuân cho tính năng nhớ tôi. nếu tôi lấy dòng này <code> <remember-me data-source-ref="dataSource" /> </code>. mọi thứ đều hoạt động tốt. nếu dòng này trình bày, nó sẽ cố gắng tải db trước khi bất cứ điều gì khác và env chưa bao giờ được tiêm.

1

Tôi đã phát hiện một lỗi tương tự cho dự án của tôi như đã đề cập here. Tôi cũng đã tìm ra, rằng một cuộc gọi về hậu quả là cần thiết để có được sessionFactory. ... và vâng, tôi cũng đang sử dụng Spring Security (có thể là nguồn gốc của sự cố).

Lớp chú thích @Configuration của tôi sử dụng @ComponentScan cho các gói chứa DAO dựa trên Hibernate và phương thức chú thích @Bean để tạo SessionFactory được DAO sử dụng. Khi chạy, một ngoại lệ được ném ra, đề cập rằng 'sessionFactory' hoặc 'hibernateTemplate' không được tìm thấy. Dường như các DAO được xây dựng trước khi SessionFactory được tạo ra. Một giải pháp cho tôi là đưa chỉ thị quét thành phần trở lại trong một tệp XML() và thay thế @ComponentScan bằng @ImportResource của tệp đó.

@Configuration 
//@ComponentScan(basePackages = "de.webapp.daocustomer", excludeFilters = {@ComponentScan.Filter(Configuration.class), @ComponentScan.Filter(Controller.class)}) 
@ImportResource({"classpath*:componentScan.xml","classpath*:properties-config.xml","classpath*:security-context.xml"}) 
public class AppConfig 
{ 
... 
@Bean 
public SessionFactory sessionFactory() throws Exception 
{ 
    AnnotationSessionFactoryBean bean = new AnnotationSessionFactoryBean(); 
    bean.setDataSource(dataSource()); 
    bean.setPackagesToScan(new String[] {"de.webapp"}); 
    bean.setHibernateProperties(hibernateProps()); 
    bean.afterPropertiesSet(); 
    return bean.getObject(); 
} 

Cũng thực tế thú vị: nếu @ComponentScan được bao gồm, một điểm ngắt được đặt trong phương thức sessionFactory() chưa bao giờ đạt được!

+0

Tôi bằng cách thông qua vấn đề đó bằng cách đặt một tệp cấu hình để quét chỉ và tải tệp cuối cùng (sử dụng @Import (xxx.class)). có rất nhiều điều cần chú ý trong khi chuyển sang cấu hình java: 1) các cuộc gọi chức năng postproperty hoặc postconstruct; 2) enum và lớp đường dẫn tài nguyên khác hơn so với dây; 3) môi trường el chuỗi khác hơn so với cách sở hữu cũ vv một số trong số họ nên được xử lý trong các máy móc mùa xuân như điều afterproperty. – jfd

1

Tôi cũng gặp vấn đề tương tự với ứng dụng mẫu xã hội mùa xuân.

Sau khi tôi chuyển đổi cấp trường @Inject sang cấp độ hàm tạo, nó hoạt động.

5

Không chắc chắn lý do nhưng sử dụng chú thích @Resource đã hiệu quả đối với tôi. @Autowired luôn trả về null.

Các vấn đề liên quan