IOC
1 Spring:
- With IOC and AOP as the core. Layered framework. Lightweight (no need to rely on other software, only JVM and container environment required).Spring 的核心结构

2 IOC
1)What is IoC?
Inversion of Control. This is a technical concept.
It addresses the management of object creation in the Java development domain:
Traditional approach: If A depends on B, an instance of B is created directly within A using "new".
IoC development approach: Instead of creating objects manually, the IoC container handles object instantiation and management for us. When we need to use an object, we request it from the IoC container.
We give up the ability to create and manage objects ourselves, but in return we gain the benefit of not having to worry about object creation, management, and related concerns.

What problem does IoC solve?

如果DaoImpl改了名字,则左侧两处代码都要改。

2 AOP Programming Concept
What is AOP?
Aspect Oriented Programming.
AOP is an extension of OOP.
Scenarios for using cross-cutting logic code are limited to: transaction control, permission validation, log printing.

<?xml version="1.0" encoding="UTF-8" ?>
<!--跟标签beans,里面配置一个又一个的bean子标签,每一个bean子标签都代表一个类的配置-->
<beans>
<!--id标识对象,class是类的全限定类名-->
<bean id="accountDao" class="com.lagou.edu.dao.impl.JdbcAccountDaoImpl">
<property name="ConnectionUtils" ref="connectionUtils"/>
</bean>
<bean id="transferService" class="com.lagou.edu.service.impl.TransferServiceImpl">
<!--set+ name 之后锁定到传值的set方法了,通过反射技术可以调用该方法传入对应的值-->
<property name="AccountDao" ref="accountDao"></property>
</bean>
<!--配置新增的三个Bean-->
<bean id="connectionUtils" class="com.lagou.edu.utils.ConnectionUtils"></bean>
<!--事务管理器-->
<bean id="transactionManager" class="com.lagou.edu.utils.TransactionManager">
<property name="ConnectionUtils" ref="connectionUtils"/>
</bean>
<!--代理对象工厂-->
<bean id="proxyFactory" class="com.lagou.edu.factory.ProxyFactory">
<property name="TransactionManager" ref="transactionManager"/>
</bean>
</beans>
3 Singleton Pattern (only one instance):
The constructor must be privatized to prevent instantiation using "new".
lazy mode
package com.qcby.singleton; public class LazySingleton { private static LazySingleton instance; private LazySingleton(){} public static synchronized LazySingleton getInstance() { if(instance == null) { instance = new LazySingleton(); } return instance; } }
hungry mode:
package com.qcby.singleton; public class HungrySingleton { private HungrySingleton() {} private static final HungrySingleton instance = new HungrySingleton(); public static HungrySingleton getInstance() { return instance; } }
create objects through xml
package com.lagou.edu.factory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class BeanFactory {
//读取xml
//对外提供几口
private static Map<String, Object> map = new HashMap<>();
static {
InputStream inputStream = BeanFactory.class.getClassLoader().getResourceAsStream("bean.xml");
SAXReader saxReader = new SAXReader();
try {
Document document = saxReader.read(inputStream);
Element root = document.getRootElement();
List<Element> elements = root.selectNodes("//bean");
for(Element bean : elements){
String id = bean.attributeValue("id");
String clazz = bean.attributeValue("class");
Class<?> aClass = Class.forName(clazz);
Object o = aClass.newInstance();
map.put(id, o);
}
//实例化完成后,维护对象的关系 有properties诉求的就有传值需求
List<Element> propertiesElements = root.selectNodes("//properties");
for(Element bean : propertiesElements) {
String name = bean.attributeValue("name");
String ref = bean.attributeValue("ref");
//找到处理当前关系的bean
Element parent = bean.getParent();
String parentId = parent.attributeValue("id");
Object po = map.get(parent.attributeValue("id"));
Method [] methods = po.getClass().getMethods();
for(Method method : methods){
if(method.getName().equalsIgnoreCase("set"+name)){
method.invoke(po, map.get(ref));
}
}
//
map.put(parentId, po);
}
} catch (DocumentException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
public static Object getBean(String name){
return map.get(name);
}
}
accountDao.updateAccountByCardNo(to); int c = 1/0; accountDao.updateAccountByCardNo(from);
package com.lagou.edu.utils; import java.sql.Connection; import java.sql.SQLException; public class ConnectionUtils { private static ConnectionUtils connectionUtils = new ConnectionUtils(); public static ConnectionUtils getInstance(){ return connectionUtils; } private ThreadLocal<Connection> local = new ThreadLocal<>(); private ConnectionUtils() { } public Connection getCurrentThreadConn() throws SQLException { Connection connection = local.get(); if(connection == null) { connection = DruidUtils.getInstance().getConnection(); local.set(connection); } return connection; } }
package com.lagou.edu.service.impl; import com.lagou.edu.utils.ConnectionUtils; import java.sql.Connection; import java.sql.SQLException; public class TransferServiceImpl { public void transfer() throws SQLException { Connection connection = ConnectionUtils.getInstance().getCurrentThreadConn(); try { //关闭自动提交事务 connection.setAutoCommit(false); //提交事务 connection.commit(); } catch (Exception e){ e.printStackTrace();; //回滚事务 connection.rollback(); } } }

-
Static Proxy: Each interface corresponds to one proxy class.
-
Dynamic Proxy:
-
No need to create a new proxy class for every business logic.
-
JDK Dynamic Proxy.
public Object getJdkProxy(Object obj) {
// 获取代理对象
return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
try{
// 开启事务(关闭事务的自动提交)
transactionManager.beginTransaction();
result = method.invoke(obj,args);
// 提交事务
transactionManager.commit();
}catch (Exception e) {
e.printStackTrace();
// 回滚事务
transactionManager.rollback();
// 抛出异常便于上层servlet捕获
throw e;
}
return result;
}
});
}
Proxy Factory reflection machganism
package com.lagou.edu.proxy.dynamicproxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class ProxyFactory { private ProxyFactory() { } private static ProxyFactory proxy = new ProxyFactory(); public static ProxyFactory getInstance() { return proxy; } public Object getJdkProxy(Object obj) { return Proxy.newProxyInstance( obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //写增强逻辑 Object result; System.out.println("start"); result = method.invoke(obj, args); System.out.println("end"); return result; } }); } }

浙公网安备 33010602011771号