SpringMVC4 + Hibernate4 整合, 使用Java配置

1.Maven依赖:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.mylab.xbmc</groupId>
    <artifactId>LibManager</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <slf4j.version>1.7.7</slf4j.version>
        <logback.version>1.1.2</logback.version>
        <junit.version>4.11</junit.version>
        <spring.version>4.1.2.RELEASE</spring.version>
        <mysql.version>5.1.34</mysql.version>
        <dbcp.version>2.0.1</dbcp.version>
        <myBatis.version>3.2.8</myBatis.version>
        <myBatisSpring.version>1.2.2</myBatisSpring.version>
        <hibernate.version>4.3.7.Final</hibernate.version>
        <jdk.version>1.8</jdk.version>
        <jetty.version>9.2.5.v20141112</jetty.version>
        <character.Encoding>UTF-8</character.Encoding>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    </properties>

    <build>
        <finalName>LibManager</finalName>
        <plugins>
            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>${jetty.version}</version>
                <configuration>
                    <!--参考: http://www.eclipse.org/jetty/documentation/current/jetty-maven-plugin.html-->
                    <httpConnector>
                        <host>127.0.0.1</host>
                        <port>8080</port>
                    </httpConnector>
                    <scanIntervalSeconds>5</scanIntervalSeconds>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${logback.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.slf4j</groupId>
                    <artifactId>slf4j-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-access</artifactId>
            <version>${logback.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <version>${dbcp.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
</project>


2.配置Serlvet容器

package org.mylab.xbmc.libmanager.config;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.*;
import java.util.EnumSet;

/**
 * 配置Servlet容器, 加载Spring框架
 * Created by CasparLi on 11/25/2014.
 */
public class WebContainerInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {

        //1、springmvc上下文
        AnnotationConfigWebApplicationContext springMvcContext = new AnnotationConfigWebApplicationContext();
        springMvcContext.register(MainConfig.class);
        springMvcContext.setServletContext(servletContext);

        //2、DispatcherServlet
        DispatcherServlet dispatcherServlet = new DispatcherServlet(springMvcContext);
        ServletRegistration.Dynamic dynamic = servletContext.addServlet("dispatcherServlet", dispatcherServlet);
        dynamic.setLoadOnStartup(1);
        dynamic.addMapping("/");

        //3、CharacterEncodingFilter
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("UTF-8");
        FilterRegistration filterRegistration = servletContext.addFilter("characterEncodingFilter", characterEncodingFilter);
        filterRegistration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "/");
    }
}

3.配置Spring

package org.mylab.xbmc.libmanager.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

/**
 * Spring主配置文件
 * Created by CasparLi on 11/25/2014.
 */
@Configuration
@EnableWebMvc
@ComponentScan("org.mylab.xbmc")
@PropertySource(value = "classpath:config.properties", ignoreResourceNotFound = true)
public class MainConfig {

    @Bean
    public UrlBasedViewResolver setupViewResolver() {
        UrlBasedViewResolver resolver = new UrlBasedViewResolver();
        resolver.setPrefix("/views/");
        resolver.setSuffix(".jsp");
        resolver.setViewClass(JstlView.class);
        return resolver;
    }

    /**
     * 配合@PropertySource 注解 处理properties文件
     *
     * @return PropertySourcesPlaceholderConfigurer
     */
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

}


4.配置Hibernate


package org.mylab.xbmc.libmanager.config;

import org.apache.commons.dbcp2.BasicDataSource;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

/**
 * 音乐库数据源配置
 * Created by CasparLi on 11/25/2014.
 */
@Configuration
@EnableTransactionManagement
@PropertySource("classpath:dataSource.properties")
@ComponentScan(basePackages = {"org.mylab.xbmc.libmanager"})
public class MusicDataSourceConfig {

    private static Logger logger = LoggerFactory.getLogger(MusicDataSourceConfig.class);

    @Value("${ds.music.driver}")
    String dsMusicDriver;
    @Value("${ds.music.url}")
    String dsMusicURL;
    @Value("${ds.music.username}")
    String dsMusicUsername;
    @Value("${ds.music.password}")
    String dsMusicPassword;

    @Bean(name = "musicDataSource")
    public DataSource dataSource() throws PropertyVetoException {
        logger.info("DataSource driver:{} url:{} username:{} password:{}", dsMusicDriver, dsMusicURL, dsMusicUsername, dsMusicPassword);
        BasicDataSource ds = new BasicDataSource();
        ds.setDriverClassName(dsMusicDriver);
        ds.setUrl(dsMusicURL);
        ds.setUsername(dsMusicUsername);
        ds.setPassword(dsMusicPassword);
        ds.setDefaultAutoCommit(false);
        return ds;
    }

    @Autowired
    @Qualifier("musicDataSource")
    @Bean(name = "musicSessionFactory")
    public LocalSessionFactoryBean sessionFactory(DataSource dataSource) throws Exception {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setPackagesToScan("org.mylab.xbmc.libmanager.bo.music");
//        sessionFactory.setPackagesToScan(new String[]{"org.mylab.xbmc.libmanager.bo.music"});
//        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
    }

    @Autowired
    @Qualifier("musicSessionFactory")
    @Bean
    public PlatformTransactionManager transactionManager(SessionFactory sessionFactory) throws PropertyVetoException {
        HibernateTransactionManager txManager = new HibernateTransactionManager();
        txManager.setSessionFactory(sessionFactory);
        return txManager;
    }
}


你可能感兴趣的:(spring,Hibernate,JavaConfig)