1.基于XML的配置
1.1 pom文件
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.2.RELEASE</version> </dependency>
1.2 创建配置文件并导入头
<?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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
1.3在配置文件中配置类
<!---配置service --> <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"> </bean> <!-- 配置dao --> <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl"></bean>
1.4测试SpringBoot环境是否搭配完成
public static void main(String[] args) { //1.使用ApplicationContext接口,就是在获取spring容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml"); //2.根据bean的id获取对象 IAccountService aService = (IAccountService) ac.getBean("accountService"); System.out.println(aService); IAccountDao aDao = (IAccountDao) ac.getBean("accountDao"); System.out.println(aDao); }
1.5一些细节
1 BeanFactory 和ApplicationContext 的区别
1 ApplicationContext 接口的实现类
1.6 bean标签
2. Spring AOP笔记
2.1 使用JDK官方的Proxy代理增强解决数据库事务问题
public class BeanFactory { final TransactionManager txManager = new TransactionManager(); public static IAccountService getAccountService() throws IllegalAccessException, InstantiationException { //1.定义被代理对象 final IAccountService accountService = new AccountServiceImpl(); //2.创建代理对象 IAccountService proxyAccountService = (IAccountService) Proxy.newProxyInstance(accountService.getClass().getClassLoader(), accountService.getClass().getInterfaces(),new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object rtValue = null; try { //开启事务 TransactionManager.beginTransaction(); //执行业务层方法 rtValue = method.invoke(accountService, args); //提交事务 TransactionManager.commit(); }catch(Exception e) { //回滚事务 TransactionManager.rollback(); e.printStackTrace(); }finally { //释放资源 TransactionManager.release(); } return rtValue; } }); return proxyAccountService; } }
原文:https://www.cnblogs.com/amaocc/p/12358865.html