Spring学习笔记 - 第005天

用代码配置Spring IoC容器+整合hibernate

1、创建config类
@Configuration
public class AppConfig {}

@Configuration表示这是spring的配置文件

2、配置数据库连接池
    @Bean
    public DataSource DataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/hib?useUnicode=true&characterEncoding=utf8");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        dataSource.setInitialSize(10);
        dataSource.setMaxIdle(50);
        return dataSource;
    }
3、配置会话工厂
    @Bean
    public LocalSessionFactoryBean sessionFactory(DataSource dataSource) {
        LocalSessionFactoryBean bean = new LocalSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setPackagesToScan(new String[] {"com.kygo.entity"});
        Properties props = new Properties();
        props.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
        props.setProperty("hibernate.show_sql", "true");
        props.setProperty("hibernate.format_sql", "true");
        bean.setHibernateProperties(props);
        return bean;
    }
4、配置事务管理
    @Bean
    public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager();
        transactionManager.setSessionFactory(sessionFactory);
        return transactionManager;
    }
5、支持动态代理和声明式事务
@Configuration
@EnableAspectJAutoProxy
@EnableTransactionManagement
public class AppConfig {}

Spring整合struts2+hibernate

需要jar包

spring-web-4.3.7.RELEASE.jar

创建applicationContext.xml和struts.xml

struts.xml




    
    
    
    
    
        
            /WEB-INF/jsp/index.jsp
        
    
 


将action对象交给springIoC容器管理

配置web.xml
       
    
        contextConfigLocation
        classpath:applicationContext.xml
    
    
    
        struts2
        org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter
    
    
    
        struts2
        /*
    
    
    
    
        org.springframework.web.context.ContextLoaderListener
    

你可能感兴趣的:(Spring学习笔记 - 第005天)