Spring_Mybatis整合 註解配置類與xml配置檔案兩種方式分析及初始化IOC容器與監聽獲取取IOC容器

yuanjiangwei255發表於2020-12-12

Spring_Mybatis整合 註解配置類與xml配置檔案兩種方式分析及初始化IOC容器與監聽獲取取IOC容器

關於:

關於Spring_mybatis整合ApplicationContext.xml版本和@Configuration配置類版本


初始化IOC容器及監聽取IOC容器(兩種方式):

初學Spring與Mybatis整合對比註解形式與xml形式區別及整合後如何初始化IOC容器
(採用 Servlet,Mybatis,Spring) 不是您的需求請繞道,感謝!

//載入xml形式applicationContext.xml(java專案)
  ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
//載入xml形式applicationContext.xml(web專案)
<!-- 指定ioc容器(applicationContext)的位置 -->
  <context-param>
  <!-- 監聽器的父類 有個常量屬性  config_location 屬性值為 contextConfigLocation  該屬性值儲存了配置檔案的位置  -->
  	<param-name>contextConfigLocation</param-name>
  	<param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <listener>
  	 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- 配置spring-web.jar提供的監聽器 此監聽器可以在伺服器啟動時 初始化Ioc容器 Ioc容器就是 applicationContext.xml
   要初始化這個容器 得告訴監聽器這個容器在哪裡  如果不告訴的話也行 有約定 預設值()  context-param 通過這個標籤告訴他
  -->
<!--servlet中取ioc容器(本文用servlet示例)-->  
@Override
	public void init(ServletConfig config) throws ServletException {
		 ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(config.getServletContext());
		 this.newsService=(NewsService) context.getBean("newsServiceImpl");
	}


*********************************************************************************

//載入註解形式applicationContext.xml(java專案)
 ApplicationContext context
                //註解放配置類
                = new AnnotationConfigApplicationContext("cn.yuanjw.myconfig");
//載入註解形式applicationContext.xml(web專案)
//此時用的是自定義監聽器: 自定義監聽器實現類(javax.servlet.ServletContextListener)
 public void contextInitialized(ServletContextEvent arg0)  { 
    	System.out.println("tomcat啟動了");
         ApplicationContext context = new AnnotationConfigApplicationContext(applicationContext.class);
         ServletContext servletContext = arg0.getServletContext();
         servletContext.setAttribute("applicationContext", context);
    }
<!--servlet中取ioc容器(本文用servlet示例)-->  
@Override
	public void init(ServletConfig config) throws ServletException {
		ServletContext servletContext = config.getServletContext();
		ApplicationContext context = (ApplicationContext) servletContext.getAttribute("applicationContext");
		 this.newsService=(NewsService) context.getBean("newsServiceImpl");
	}

Xml形式(配置檔案):

applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!-- 標頭檔案 -->
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
	xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring https://mybatis.org/schema/mybatis-spring-1.2.xsd
		http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd
		http://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx.xsd">
	<!-- 管理資料來源及SQLSessionFactory -->
	<import resource="classpath:application-dao1.xml"/>
	<!-- 管理事務 -->
	<import resource="classpath:application-service.xml"/>
	<!-- 管理controller -->
	<import resource="classpath:application-action.xml"/>
	<!-- 管理job任務 -->(可忽略)
	<import resource="classpath:application-job3.xml"/>
	
</beans>

application-Controller.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!-- 標頭檔案 -->
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
	    http://www.springframework.org/schema/context/spring-context.xsd
	    http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx.xsd
        ">
	<!-- 開啟掃描 -->
	<context:component-scan base-package="org.yuanjw.controller"></context:component-scan>
		
</beans>

application-Service.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!-- 標頭檔案 -->
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
	    http://www.springframework.org/schema/context/spring-context.xsd
	    http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx.xsd
        ">
	<!-- 事務管理器 -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<!-- 注入資料來源 -->
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	
	<tx:advice id="txadvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="add*" propagation="REQUIRED"/>
			<tx:method name="insert*" propagation="REQUIRED"/>
			<tx:method name="save*" propagation="REQUIRED"/>
			<tx:method name="set*" propagation="REQUIRED"/>
			<tx:method name="del*" propagation="REQUIRED"/>
			<tx:method name="remove*" propagation="REQUIRED"/>
			<tx:method name="update*" propagation="REQUIRED"/>
			<tx:method name="*" read-only="true"/>
		</tx:attributes>
	</tx:advice>
	
	<aop:config>
		<aop:pointcut expression="execution(* org.yuanjw.service.impl.*.*(..))" id="pc"/>
		<aop:advisor advice-ref="txadvice" pointcut-ref="pc"/>
	</aop:config>
		
		<!-- 配置service 可以mapper首字母小寫取代理物件 也可以bytype自動裝配 -->
	<!-- 	<bean id="departmentServiceImpl" class="org.yuanjw.service.impl.DepartmentServiceImpl" >
			<property name="departmentMapper" ref="departmentMapper"></property>
		</bean> -->
		<!-- 開啟掃描 -->
	<context:component-scan base-package="org.yuanjw.service.impl"></context:component-scan>
		
</beans>

application-Dao.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!-- 標頭檔案 -->
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
	    http://www.springframework.org/schema/context/spring-context.xsd
	    http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx.xsd
        ">
<?xml version="1.0" encoding="UTF-8"?>
<!-- 標頭檔案 -->
<beans xmlns="http://www.springframework.org/schema/beans" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
	    http://www.springframework.org/schema/context/spring-context.xsd
	    http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx.xsd
        ">
	
<!-- 練習1 -->
<!-- 引入外部資源 -->
<context:property-placeholder  location="classpath:DB.properties" system-properties-mode="FALLBACK"/>
<!--建立資料來源(spring自帶資料來源) -->
<!-- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
	<property name="driverClassName" value="${driver}"></property>
	<property name="url"  value="${url}"></property>
	<property name="username"  value="${username}"></property>
	<property name="password"  value="${password}"></property>
</bean> -->
<!-- 配置資料來源2(druid資料來源) -->
	<!-- <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
		<property name="url" value="${url}"></property>
		<property name="username" value="${username}"></property>
		<property name="password" value="${password}"></property>
		<property name="driverClassName" value="${driver}"></property>
	</bean> -->
	
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="url" value="${url}"></property>
		<property name="username" value="${username}"></property>
		<property name="password" value="${password}"></property>
		<property name="driverClassName" value="${driver}"></property>
	</bean>
<!-- 配置SQLSessionFactory工廠 依賴資料來源 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
	<property name="dataSource" ref="dataSource"></property>
	<!-- 載入對映檔案 -->
		<property name="mapperLocations">
		<array>
			 <value>classpath:org/yuanjw/mapping/\*.xml</value>
		</array>
		</property>
		<property name="plugins">
			<array>
				<bean class="com.github.pagehelper.PageInterceptor"></bean>
			</array>
		</property>
	 	<property name="typeAliasesPackage" value="org/yuanjw/domain"></property> 
		
</bean>
<!-- 有了SQLSessionFactory之後 需要通過它建立代理物件 掃描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="org.yuanjw.mapper"></property>
	<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
		
</beans>

註解形式(配置類):

DatabaseConfig.java:
(為什麼會專門拆出一個配置類?)
答:@Value與@PropertySource()在 一個配置類中會為空
處理方式:
(1)在配置類前面加上@Scope(“prototype”):真正開發時並不推薦
(2)拆分配置檔案:把資料庫相關配置拆分出去
原處:https://blog.csdn.net/qq_41699954/article/details/107920818
好了繼續:

@Configuration
@PropertySource("classpath:database.properties")
public class DatabaseConfig {
	 @Value("${url}") private String url;
	  @Value("${driver}")private  String driver;
	  @Value("${user}")private String user;
	  @Value("${password}")private String password;
	//配置資料來源
	@Bean  
	public DriverManagerDataSource DataSource() {
		System.out.println(url+"***********");
		DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource(url,user,password);
		driverManagerDataSource.setDriverClassName(driver);
		return driverManagerDataSource;
	}
}

applicationContext.java:

package com.config;

import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
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.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.Scope;
import org.springframework.core.io.ClassPathResource;

import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.dao.EasybuyCollectDao;
import com.github.pagehelper.PageInterceptor;

@Configuration
@EnableTransactionManagement
@ComponentScan(basePackages= {"com.web.backend"
								,"com.web.pre"
								,"com.service.address.impl"
								,"com.service.news.impl"
								,"com.service.order.impl"
								,"com.service.product.impl"
								,"com.service.user.impl"
								})
@Import(DatabaseConfig.class)
public class applicationContext {
	 
	//配置sessionFactory
	@Bean 
	public SqlSessionFactoryBean sqlSessionFactory(@Autowired DriverManagerDataSource dataSource) {
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		sqlSessionFactoryBean.setDataSource(dataSource);
		sqlSessionFactoryBean.setTypeAliasesPackage("com.entity");
//		ClassPathResource classPathResource =new ClassPathResource("classpath:com/dao/*.xml");
//		//Resource[] resources = new ClassPathResource[] {classPathResource};
		//ClassPathResource classPathResource = new ClassPathResource("EasybuyOrderMapper.xml",EasybuyCollectDao.class);
		sqlSessionFactoryBean.setMapperLocations(
				new ClassPathResource[] {
						new ClassPathResource("EasybuyOrderMapper.xml",EasybuyCollectDao.class)
						,new ClassPathResource("EasybuyUserAddressMapper.xml",EasybuyCollectDao.class)
						,new ClassPathResource("EasybuyUserMapper.xml",EasybuyCollectDao.class)
						,new ClassPathResource("NewsMapper.xml",EasybuyCollectDao.class)
						,new ClassPathResource("OrderDetailMapper.xml",EasybuyCollectDao.class)
						,new ClassPathResource("OrderMapper.xml",EasybuyCollectDao.class)
						,new ClassPathResource("ProductCategoryMapper.xml",EasybuyCollectDao.class)
						,new ClassPathResource("ProductMapper.xml",EasybuyCollectDao.class)
				});
		sqlSessionFactoryBean.setPlugins(
				new Interceptor[] {
						new PageInterceptor()
					});
		return sqlSessionFactoryBean;
	}
	@Bean
	public MapperScannerConfigurer mapperScannerConfigurer() {
		MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
		mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
		mapperScannerConfigurer.setBasePackage("com.dao");
		return mapperScannerConfigurer;
	}
	@Bean
	public DataSourceTransactionManager dataSourceTransactionManager(@Autowired DriverManagerDataSource dataSource) {
		DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
		dataSourceTransactionManager.setDataSource(dataSource);
		return dataSourceTransactionManager;
	}
}

經對比發現:xml配置更為簡單高效(針對於註解形式不滿意點在於setMapperLocations)
無法使用萬用字元!!!)
註解形式可完全啊刪除xml
感謝查閱!第一次寫部落格,如有錯誤請指正,感謝!

相關文章