SSM框架新特性关于用Java配置类完全代替XML

项目目录结构

 

从Spring3.0,@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被@Bean注解的方法,

这些方法将会被AnnotationConfigApplicationContext或AnnotationConfigWebApplicationContext类进行扫描,

并用于构建bean定义,初始化Spring容器 

  • 替代web.xml

WebApplicationInitializer.java

package javaConfiguration;

import javaConfiguration.RootConfig;
import javaConfiguration.WebConfig;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import javax.servlet.Filter;
import java.util.logging.Logger;
/*
* Spring Mvc的配置
*createDate: 2018年12月21日
* author: dz
 * */
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    private final static Logger LOG = Logger.getLogger(String.valueOf(WebAppInitializer.class));

    @Override
    protected Class<?>[] getRootConfigClasses() {
        LOG.info("root配置类初始化");
        return new Class<?>[]{RootConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        LOG.info("------web配置类初始化------");
        return new Class<?>[]{WebConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        LOG.info("------映射根路径初始化------");
        return new String[]{"/"};//请求路径映射,根路径
    }

    @Override
    protected Filter[] getServletFilters() {
        LOG.info("-----编码过滤配置-------");
        CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter("UTF-8");
        return new Filter[]{encodingFilter};
    }
}

WebConfig.java

package javaConfiguration;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.validation.Validator;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 *<p>Title: WebConfig.java</p>
 *<p>Description: 配置类,用于定义DispatcherServlet上下文的bean</p>
 *<p>CreateDate: 2018年12月20日</p>
 *@author dz
 */
@Configuration
@EnableWebMvc
@EnableAspectJAutoProxy
@ComponentScan(basePackages = "com.dznfit.controller")
public class WebConfig implements WebMvcConfigurer{


    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.jsp("/WEB-INF/view/",".jsp");
    }

}

这是对应spring-mvc.xml的部分
@Configuration及其下的@bean(比如注册了JSP的视图解析器的bean等springmvc常配置的bean)      

Configuration注解就是告诉Spring这个是一个配置文件类,这里配置的Bean要交给Spring去管理
@ComponentScan("com.dznfit.controller") //相当于<context:component-scan base-package="com.dznfit.controller"          

配合@Controller注册Controller的bean
@EnableWebMvc //相当于 <mvc:annotation-driven/>   启用Spring MVC支持
至此spring-mvc.xml完全被代替。

 

RootConfig.java

package javaConfiguration;

import javaConfiguration.root.MybatisConfig;
import javaConfiguration.root.ShiroConfig;
import org.springframework.context.annotation.*;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

/**
 *<p>Title: RootConfig.java</p>
 *<p>Description: 配置类,用于管理ContextLoadListener创建的上下文的bean</p>
 *<p>CreateDate: 2018年12月20日</p>
 *@author dz
 */
@Configuration
@ComponentScan(basePackages = {"com.dznfit.service"})
@PropertySource("classpath:jdbc.properties")
@Import({MybatisConfig.class, ShiroConfig.class})
public class RootConfig {
    @Bean
    public static PropertySourcesPlaceholderConfigurer sourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

MybatisConfig.java

package javaConfiguration.root;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mchange.v2.c3p0.DataSources;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.io.IOException;
/**
 *<p>Title: DruidDataSourceConfig.java</p>
 *<p>Description: 数据源属性配置</p>
 *<p>CreateDate: 2018年12月20日</p>
 *@author dz
 */
@Configuration
@MapperScan(basePackages = "com.dznfit.dao")
@EnableTransactionManagement
public class MybatisConfig {

    @Value("${driver}")
    private String driver;

    @Value("${url}")
    private String url;

    @Value("${name}")
    private String user;

    @Value("${password}")
    private String password;

    @Autowired
    private Environment environment;

    @Bean("dataSource")
    public DataSource dataSourceConfig() throws PropertyVetoException {
        // 使用c3p0
        ComboPooledDataSource source = new ComboPooledDataSource();
        source.setDriverClass(driver);
        source.setJdbcUrl(url);
        source.setUser(user);
        source.setPassword(password);
        return source;
    }

    @Bean("sqlSessionFactoryBean")
    public SqlSessionFactoryBean sqlSessionFactoryBeanConfig() throws PropertyVetoException, IOException {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(this.dataSourceConfig());
        factoryBean.setTypeAliasesPackage("com.dznfit.entity");
        factoryBean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

        factoryBean.setMapperLocations(resolver.getResources("Mapper/*.xml"));
        return factoryBean;
    }

    @Bean("transactionManager")
    public DataSourceTransactionManager dataSourceTransactionManagerConfig() throws PropertyVetoException {
        DataSourceTransactionManager manager = new DataSourceTransactionManager();
        manager.setDataSource(this.dataSourceConfig());
        return manager;
    }
}

ShiroConfig.java

package javaConfiguration.root;

import org.springframework.context.annotation.Configuration;

@Configuration
public class ShiroConfig {
}

 

这部分相当于spring-*.xml中管理的常用dao(mapper)、Service

@Configuration标记这是一个配置类
@ComponentScan配合@Repository、 @Service注册dao和Service的bean

@MapperScan("com.dznfit.service")     
@MapperScan("com.dznfit.dao")
//Mybatis mapper.class的位置相当MapperScannerConfigurer 的bean      

如果用的是mybatis的话,用@MapperScan注册mapper的bean   

为了方便管理增加灵活性把它们分开不同的类来注册,使用@Import引入

@Import({MybatisConfig.class, ShiroConfig.class})

@Configuration及其下的@bean(比如注册了DataSource和sqlSessionFactory等的bean)       

Configuration注解就是告诉Spring这个是一个配置文件类,这里配置的Bean要交给Spring去管理

@EnableTransactionManagement 相当于<tx:annotation-driven />

此文章参考:javaConfiguration

源码下载:dznf147

 

告辞...

posted on 2018-12-21 09:00  东子z  阅读(1307)  评论(0编辑  收藏  举报

导航