1

我使用 Spring 版本 3.2.2.RELEASE。

我想用 hibernate 创建一个 webapp 并具有以下配置:

public class LifepulseServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

@Override
protected Class<?>[] getRootConfigClasses() {
    return new Class[] { PersistenceConfig.class};
}

@Override
protected Class<?>[] getServletConfigClasses() {
    return new Class[] { LifepulseWebConfig.class };
}

@Override
protected String[] getServletMappings() {
    return new String[] { "/" };
}

@Override
protected WebApplicationContext createRootApplicationContext() {
    return super.createRootApplicationContext();
}

}

我的两个带有 @Configuration 注释的文件如下所示:

我的PersistenceConfig应该用于 ContextLoaderListener:

@Configuration
@EnableTransactionManagement(proxyTargetClass=true, mode=AdviceMode.PROXY)
public class PersistenceConfig{

Logger logger = LoggerFactory.getLogger(PersistenceConfig.class);

/** The Application Context. */
@Autowired
ApplicationContext context;

/**
 * Gets the database url.
 *
 * @return the database url
 */
@Bean(name="databaseUrl")
public String getDatabaseUrl(){
    return "jdbc:mysql://localhost/lifepulse";
}

/**
 * Gets the session factory properties.
 *
 * @return the session factory properties
 */
@Bean(name="sessionFactoryProperties")
public Properties getSessionFactoryProperties(){


    Properties props = new Properties();
    props.put("hibernate.dialect", MySQL5InnoDBDialect.class.getName());
    props.put("hibernate.hbm2ddl.auto", "create-drop");
    props.put("hibernate.show_sql", "true");
    props.put("hibernate.format_sql", "true");
    return props;
}


/** The Constant ANNOTATED_CLASSES. */
@SuppressWarnings("unchecked")
private static final Class<? extends Serializable>[] ANNOTATED_CLASSES=new Class[]{
    Melder.class,
    LogEntry.class
};


/**
 * Gets the annotated classes.
 *
 * @return the annotated classes
 */
private static Class<? extends Serializable>[] getAnnotatedClasses(){
    return ANNOTATED_CLASSES;
}

/**
 * Gets the data source.
 * This bean represents the application's MYSQL datasource, without using xml.
 *
 * @return the data source
 */
@Bean
public DataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl(getDatabaseUrl());
    dataSource.setUsername("lifepulse");
    dataSource.setPassword("lifepulse");
    return dataSource;
}

/**
 * Session factory.
 * This bean represents the Hibernate Session Factory. By declaring this bean
 * it can easily be injected into Spring DAOs later on.
 * 
 * @return the local session factory bean
 */
@Bean
public LocalSessionFactoryBean sessionFactory() {

    LocalSessionFactoryBean factory = new LocalSessionFactoryBean();
    factory.setAnnotatedClasses(getAnnotatedClasses());     
    factory.setHibernateProperties(getSessionFactoryProperties());
    factory.setDataSource(dataSource());
    return factory;
}

@Bean()
public GenericDao genericDao() {
    return new HibernateDaoImpl();
}

@Bean
PlatformTransactionManager txManager(){
    HibernateTransactionManager htm = new HibernateTransactionManager(sessionFactory().getObject());
    return htm;
}
}

我的LifepulseWebConfig应该用于 DispatcherSerlvet:

@Configuration
@EnableWebMvc
@ComponentScan(value= {"com.ansiworks.lifepulse.controllers"})
@EnableTransactionManagement(proxyTargetClass=true, mode=AdviceMode.PROXY)
public class LifepulseWebConfig extends WebMvcConfigurerAdapter{ 
@Autowired
ApplicationContext context;


@Bean
ViewResolver viewResolver(){
    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    //resolver.setPrefix("");
    resolver.setSuffix(".jsp");
    return resolver;
}

@Bean
MainService mainService(){
    return new MainServiceImpl();
}

}

此配置不起作用。dispathcer servlet 不会加载我的 PersistenceConfig,因此 bean 不会继承到 LifepulseWebConfig。

但是:当我将PersistenceConfig添加到方法LifepulseServletInitializer#getServletConfigClasses()的类数组中时,一切正常。但是......我不能以这种方式使用sprint-security......

我究竟做错了什么!?为什么 ContextLoaderListener 不读取LifepulseServletInitializer#getRootConfigClasses()返回的配置类?

我也尝试过这种方式(没有LifepulseServletInitializer),效果相同。我的PersistenceConfig的 bean根本没有加载......

public class MyWebAppInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext container) {
      // Create the 'root' Spring application context
      AnnotationConfigWebApplicationContext rootContext =
        new AnnotationConfigWebApplicationContext();
      rootContext.register(PersistenceConfig.class);

      // Manage the lifecycle of the root application context
      container.addListener(new ContextLoaderListener(rootContext));

      // Create the dispatcher servlet's Spring application context
      AnnotationConfigWebApplicationContext dispatcherContext =
        new AnnotationConfigWebApplicationContext();
      dispatcherContext.register(LifepulseWebConfig.class);

      // Register and map the dispatcher servlet
      ServletRegistration.Dynamic dispatcher =
        container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
      dispatcher.setLoadOnStartup(1);
      dispatcher.addMapping("/");
    }

}
4

0 回答 0