1. 程式人生 > >全註解配置SSM

全註解配置SSM

新建Maven工程,打包方式 war:

修改pom.xml 檔案增加依賴:

<dependencies>
		<!-- 配置spring-webmvc就不用配spring-context了 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>4.3.9.RELEASE</version>
		<
/dependency> <!-- jackson和fastjson,可以任選一個. --> <!-- <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.5</version> </dependency> --> <dependency> <groupId>
com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.38</version> </dependency> <!-- 根據資料庫版本選擇connector4j版本. --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <
version>
8.0.12</version> </dependency> <!-- springJDBC和spring主版本相匹配 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.9.RELEASE</version> </dependency> <!-- MyBatis主包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.8</version> </dependency> <!-- 整合包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> <scope>test</scope> </dependency> <!-- druid連線池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.10</version> </dependency> <!-- log4j 作用域:provided --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> <scope>provided</scope> </dependency> <!-- shiro安全框架 --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.3.2</version> </dependency> <!-- 面向切面2個依賴 --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.8.9</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.9</version> </dependency> <!-- 通用Mapper --> <dependency> <groupId>com.github.abel533</groupId> <artifactId>mapper</artifactId> <version>3.0.1</version> </dependency> <!-- 分頁外掛 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>3.2.1</version> </dependency> <!-- 傳送郵件驗證 --> <dependency> <groupId>javax.mail</groupId> <artifactId>javax.mail-api</artifactId> <version>1.5.5</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.mail/mail --> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.5.0-b01</version> </dependency> <!-- redis 連線 --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.6.2</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.2</version> <configuration> <!-- 這裡是設定不檢測web.xml --> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <!-- 這裡是設定每次update專案後的JDK版本過低bug --> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build>

整體結構圖:

在這裡插入圖片描述

配置替代web.xml 的啟動類

WebAppInitializer.class

import javax.servlet.Filter;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
/**
 * 關於 AbstractAnnotationConfigDispatcherServletInitializer 在 Servlet 3.0
 * 環境下,Servlet 容器會在 classpath 下搜尋實現了 javax.servlet.ServletContainerInitializer
 * 介面的任何類,找到之後用它來初始化 Servlet 容器。
 * 
 * Spring 實現了以上介面,實現類叫做 SpringServletContainerInitializer, 它會依次搜尋實現了
 * WebApplicationInitializer的任何類,並委派這個類實現配置。 之後,Spring 3.2 開始引入一個簡易的
 * WebApplicationInitializer 實現類, 這就是
 * AbstractAnnotationConfigDispatcherServletInitializer。 所以
 * SpittrWebAppInitializer 繼承
 * AbstractAnnotationConfigDispatcherServletInitializer之後, 也就是間接實現了
 * WebApplicationInitializer,在 Servlet 3.0 容器中,它會被自動搜尋到,被用來配置 servlet 上下文。
 *
 */
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

	/**
	 *  註冊順序->listener->filter(Shiro安全框架)->servlet(SpringMVC)..
	 *  必須按照順序註冊,所以必須重寫onStarup
	 */
	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
//    	super.onStartup(servletContext);
		registerContextLoaderListener(servletContext);
		// 在這裡註冊shiro過濾器
		registerSiroFilter(servletContext);

		registerDispatcherServlet(servletContext);

	}
	
	/**
	 * 註冊過濾器解決post亂碼問題
	 */
	@Override
	protected Filter[] getServletFilters() {
		CharacterEncodingFilter filter=new CharacterEncodingFilter();
		filter.setEncoding("utf-8");
		filter.setForceEncoding(true);
		return new Filter[] {filter};
		
	}
	
	/**
	 * 註冊shiro配置
	 * @param servletContext
	 */
	private void registerSiroFilter(ServletContext servletContext) {
		// 註冊Filter物件
		// 什麼時候需要採用此方式進行註冊?
		// 專案沒有web.xml並且此filter不是自己寫的
		FilterRegistration.Dynamic dy = servletContext.addFilter("filterProxy", DelegatingFilterProxy.class);
		dy.setInitParameter("targetBeanName", "shiroFilterFactoryBean");
		dy.addMappingForUrlPatterns(null, // EnumSet<DispatcherType>//不寫就是預設所有的.
				false, // 是否精確匹配
				"/*");// url-pattern
	}

	/**
	 * 此方法負責載入Service和其他第三方包的初始化配置如service層和DataAccessObject層的框架和類
	 */
	@Override
	protected Class<?>[] getRootConfigClasses() {
		return new Class[] { AppRootConfig.class,AppShiroConfig.class,AppRedisConfig.class };
	}

	/**
	 * 這裡寫入用以取代Spring和SpringMVC的配置檔案
	 */
	@Override
	protected Class<?>[] getServletConfigClasses() {
		return new Class[] { AppServletConfig.class };
	}

	/**
	 * 這裡配置預設前端控制器.這裡所有匹配*.do的訪問都會被捕捉到. 也可以配置為"/" 不會攔截.jsp /* 全部攔截   不能使用.log 結尾,否則阿里巴巴 fastjson轉換報錯
	 */
	@Override
	protected String[] getServletMappings() {
		return new String[] {"*.xiami"};
	}
}

持久層Mybatis配置類:

/** 配置JDBC,MyBatis相關配置 每個配置類專注於自己的內容*/
@Configuration
@ComponentScan(value = "com.xiami", excludeFilters = { // 這裡需要把MVC相關注解排除,否則test會報錯!~無法建立bean工廠
@Filter(classes = { Controller.class, ControllerAdvice.class, Configuration.class }) })
@PropertySource("classpath:property/jdbc.properties") // 讀取JDBC配置檔案
@MapperScan("com.xiami.**.dao")//包掃描 介面
@EnableAspectJAutoProxy // 啟動切面
//@EnableTransactionManagement//啟動事務
public class AppRootConfig {
	/**
	 * 讓系統支援多個properties檔案應用,否則shiro會出錯
	 * 
	 * @return
	 */
	@Bean
	public PropertySourcesPlaceholderConfigurer newPropertyPlaceholderConfigurer() {
		return new PropertySourcesPlaceholderConfigurer();
	}
	/**
	 * druid相關配置
	 * @param driverClass
	 * @param jdbcUrl
	 * @param username
	 * @param password
	 * @return
	 */
	@Bean(value = "dataSource", initMethod = "init", destroyMethod = "close") // <bean id="dataSource"
	@Lazy(false)
	public DataSource newDataSource(@Value("${jdbcDriver}") String driverClass, @Value("${jdbcUrl}") String jdbcUrl,
			@Value("${jdbcUser}") String username, @Value("${jdbcPassword}") String password) {

		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setUrl(jdbcUrl);
		dataSource.setDriverClassName(driverClass);
		dataSource.setUsername(username);
		dataSource.setPassword(password);
		// 配置其他東西自行使用set方法設定
		return dataSource;

	}

	/**
	 * 整合MyBatis配置檔案,接管SqlSessionFactory
	 * @param dataSource
	 * @return
	 * @throws IOException
	 */
	@Bean
	@Lazy(false)
	public SqlSessionFactoryBean newSqlSessionFactory(@Autowired /* 根據屬性型別自動裝配,可以省略 */ DataSource dataSource)
			throws IOException {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(dataSource);
		Resource[] mapperLocations = new PathMatchingResourcePatternResolver()
				.getResources("classpath:mapper/*Mapper.xml");
		bean.setMapperLocations(mapperLocations);
		// 設定啟動駝峰自動對映
		org.apache.ibatis.session.Configuration conn = new org.apache.ibatis.session.Configuration();
		conn.setMapUnderscoreToCamelCase(true);
		bean.setConfiguration(conn);
		
		//配置myBatis,pageHelper外掛
		PageHelper pHelper=new PageHelper();
		Properties p=new Properties();
		p.setProperty("resonable", "true");
		p.setProperty("dialect", "mysql");
		p.setProperty("rowBoundsWithCount", "true");
		pHelper.setProperties(p);
		
		//配置通用mapper
		MapperInterceptor interceptor=new MapperInterceptor();
		Properties mapperProperties=new Properties();
		mapperProperties.setProperty("IDENTITY","MYSQL");
		mapperProperties.setProperty("mappers", "com.xiami.common.mapper.CommonMapper");
		interceptor.setProperties(mapperProperties);
		
		Interceptor[] mapper = {pHelper,interceptor};
		bean.setPlugins(mapper);
		return bean;
	}

	@Bean("txManager") // 需要在最頂端用註解@Enable來啟用事物管理器
	public DataSourceTransactionManager newData(DataSource dSource) {
		DataSourceTransactionManager dstm = new DataSourceTransactionManager(dSource);
		return dstm;
	}

	/*切面類*/
	@Bean//將aop類載入到容器
	public AopService getAopService(){
		AopService aopService= new AopService();
		return aopService;
	}
	 	
	/*
	 * public MapperScannerConfigurer newMapperScannerConfigurer() {
	 * MapperScannerConfigurer msc=new MapperScannerConfigurer();
	 * msc.setBasePackage("com.jt.**.dao");
	 * msc.setSqlSessionFactoryBeanName("newSqlSessionFactory"); return msc; }
	 */// 用上面那個@MapperScan("com.jt.**.dao")代替
}

配置SpringMVC的配置類:

//通常讓每個的配置檔案只幹自己的事,就設定過濾器
@ComponentScan(value="com.xiami",includeFilters={@Filter(classes= {Controller.class,ControllerAdvice.class})},useDefaultFilters=false)//這裡配置包掃描路徑
@EnableWebMvc//啟用MVC預設配置
@Configuration//有包掃描則可以省略
public class AppServletConfig extends WebMvcConfigurerAdapter{
	/**
	 * 配置檢視解析器
	 */
	@Override
	public void configureViewResolvers(ViewResolverRegistry registry) {
	   registry.jsp("/WEB-INF/pages/",".html");
	}
	
	/**
	 * 加入基於註解方式整合fastjson
	 * 可以參考新增如下配置.
	 */
	
	//整合fastjson庫
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    	//1.構建MessageConverter物件
    	FastJsonHttpMessageConverter msConverter = new FastJsonHttpMessageConverter();
    	//2.配置MessageConverter物件
    	//2.1設定fastjson基本配置
    	FastJsonConfig config = new FastJsonConfig();
    	config.setSerializeConfig