這篇文章為spring回顧總結的第二篇,本篇主要分為兩個部分,分別是spring的bean工廠的實現.spring的aop實現原理,這兩部分也是面試當中問的比較多的. spring的bean工廠的實現 spring的bean工廠的實現可以有以下三種方式 1. 靜態工廠實現 配置文件: 2. 實例工廠 ...
這篇文章為spring回顧總結的第二篇,本篇主要分為兩個部分,分別是spring的bean工廠的實現.spring的aop實現原理,這兩部分也是面試當中問的比較多的.
spring的bean工廠的實現
spring的bean工廠的實現可以有以下三種方式
- 靜態工廠實現
public class StaticCarFactory {
public static Map<String,Car> carMap = new HashMap<>();
static {
carMap.put("audi",new Car("audi","330000"));
carMap.put("ford",new Car("ford","40000"));
}
public static Car getCar( String name){
return carMap.get(name);
}
}
配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--通過靜態工廠方法配置bean,不是配置靜態工廠方法實例,而是bean的實例
factory-method:指向靜態工廠方法的名稱
constructor-arg:如果工廠方法需要傳入參數,使用constructor-arg配置傳入的參數
-->
<bean id="car1" class="com.springtest.beanFactory.StaticCarFactory"
factory-method="getCar">
<constructor-arg value="audi"/>
</bean>
<!--配置工廠實例-->
<bean id="carFactory" class="com.springtest.beanFactory.InstanceCarFactory">
</bean>
<!-- 通過實例工廠方法來配置bean-->
<bean id="car2" factory-bean="carFactory" factory-method="getCar">
<constructor-arg value="ford"/>
</bean>
</beans>
- 實例工廠實現
public class InstanceCarFactory {
private Map<String, Car> cars = null;
public InstanceCarFactory() {
cars = new HashMap<String, Car>();
cars.put("audi", new Car("audi", "300000"));
cars.put("ford", new Car("ford", "600000"));
}
public Car getCar(String name) {
return cars.get(name);
}
}
配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--通過靜態工廠方法配置bean,不是配置靜態工廠方法實例,而是bean的實例
factory-method:指向靜態工廠方法的名稱
constructor-arg:如果工廠方法需要傳入參數,使用constructor-arg配置傳入的參數
-->
<bean id="car1" class="com.springtest.beanFactory.StaticCarFactory"
factory-method="getCar">
<constructor-arg value="audi"/>
</bean>
<!--配置工廠實例-->
<bean id="carFactory" class="com.springtest.beanFactory.InstanceCarFactory">
</bean>
<!-- 通過實例工廠方法來配置bean-->
<bean id="car2" factory-bean="carFactory" factory-method="getCar">
<constructor-arg value="ford"/>
</bean>
</beans>
- 實現spring提供的FactoryBean介面
/**
* 自定義的factorybean需要實現spring提供的factorybean介面
*/
public class CarFactoryBean implements FactoryBean<Car> {
private String brand;
public void setBrand(String brand) {
this.brand = brand;
}
@Override
public Car getObject() throws Exception {
return new Car("BMW","430000");
}
@Override
public Class<?> getObjectType() {
return Car.class;
}
@Override
public boolean isSingleton() {
return true;
}
}
配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--通過factorybean來配置bean的實例
class:指向factorybean的全類名
property:配置factorybean的屬性
但是實際返回的是實例確實是factorybean的getobject()方法返回的實例
-->
<bean id="car1" class="com.springtest.factoryBean.CarFactoryBean">
<property name="brand" value="BMW"></property>
</bean>
</beans>
spring的aop的實現原理
學習aop,首先要瞭解兩點
什麼是aop?
在軟體業,AOP為Aspect Oriented Programming的縮寫,意為:面向切麵編程,通過預編譯方式和運行期動態代理實現程式功能的統一維護的一種技術。AOP是OOP的延續,是軟體開發中的一個熱點,也是Spring框架中的一個重要內容,是函數式編程的一種衍生範型。利用AOP可以對業務邏輯的各個部分進行隔離,從而使得業務邏輯各部分之間的耦合度降低,提高程式的可重用性,同時提高了開發的效率。(摘自百度百科)- 為什麼要使用aop?
使用aop主要為瞭解決兩個問題:- 代碼混亂.即非核心代碼和核心代碼混在一起,難以維護或者提高維護成本,
- 代碼分散.一旦非核心代碼需要更改或者替換部分邏輯,那麼全部方法中的相關的邏輯都要改動,相當麻煩;
- 幾個關鍵詞
- Aspect(切麵) 橫切關註點
- Advice(通知) 切麵必須要完成的工作
- Target(目標) 被通知的對象
- Proxy(代理) 向目標對象應用通知之後創建的對象
- Joinpoint(連接點) 程式執行的 某個特定的位置,比如方法調用前,調用後,方法拋出異常後等.是實際存在的物理位置.
- pointcut(切點) 每個類都有多個連接點.aop通過切點定位到連接點.切點和連接點不是一對一的關係,一個切點可匹配多個連接點,切點通過org.springframework.aop.pointcut介面進行描述,使用類和方法作為連接點的查詢條件.
類比記憶:連接點相當於資料庫中的記錄,切點相當於查詢條件
.
代碼示例如下:
首先定義介面:
```
public interface Calculation {
int add(int i, int j);
int sub(int i, int j);
}定義實現類
public class CalculationImpl implements Calculation {
@Override
public int add(int i, int j) {
//業務功能前加log記錄
System.out.println("這個" + i + ";那個" + j);
int result = i + j;
System.out.println("結果是"+result);
return result;
}@Override
public int sub(int i, int j) {
System.out.println("這個" + i + ";那個" + j);
int result = i - j;
System.out.println("結果是"+result);
return result;
}
}可以看到,模擬加了log日誌的話,就要在方法核心代碼前後添加無關代碼,並且所有用到log的地方都要添加,難以維護; 下麵上改進的代碼:
public class CalculationLoggingImpl implements Calculation {
@Override
public int add(int i, int j) {
//業務功能前加log記錄
int result = i + j;
return result;
}@Override
public int sub(int i, int j) {
int result = i - j;
return result;
}
}
public class CalculationLoggingProxy {這裡是一個代理類,
/**- 要代理的對象
*/
private Calculation target;
public CalculationLoggingProxy(Calculation target){
this.target = target;
}
public Calculation getLoggingProxy() {
Calculation proxy = null;
ClassLoader loader = target.getClass().getClassLoader();
Class[] interfaces = new Class[]{Calculation.class};
//當調用代理對象其中方法時,該執行的代碼
/**
* proxy:正在返回的那個代理對象,
* method:正在被調用的方法
* args:調用方法時傳入的參數;
/
InvocationHandler handler = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String name = method.getName();
System.out.println("method:"+ name+"params:"+ Arrays.asList(args));
Object invoke = method.invoke(target, args);
System.out.println(invoke);
return invoke;
}
};
proxy = (Calculation) Proxy.newProxyInstance(loader, interfaces, handler);
return proxy;
}
}Test類:
public class Test {
public static void main(String[] args) {
//1,不使用代理
// Calculation calculation = new CalculationImpl();
// calculation.add(1,2);
// calculation.sub(3,1);
//2.使用代理
Calculation target = new CalculationLoggingImpl();
Calculation proxy = new CalculationLoggingProxy(target).getLoggingProxy();
proxy.add(1, 2);
}
}
一個簡單的aop例子就可以跑起來了,可以看到,使用了動態代理之後,可以將無關核心業務的log代碼抽取到代理類中去添加維護,並且無關被代理類究竟是哪一個,省去了很多重覆和不必要的代碼,提高了代碼的靈活性和可維護性.
- aop的實現框架
aspectJ是java社區最完整,最流行的aop框架,在Spring2.0以上版本中,可以使用基於aspectJ註解或者基於xml配置的aop.
那麼我們還是分兩步來看aspectJ實現aop的過程,先看基於註解實現的,再看基於xml配置實現的.
1. 基於註解實現
首先把類交給ioc容器管理
@Component
public class CalculationLoggingImpl implements Calculation {
@Override
public int add(int i, int j) {
//業務功能前加log記錄
int result = i + j;
return result;
}
@Override
public int sub(int i, int j) {
int result = i - j;
return result;
}
}
```
聲明一個切麵,在此需要註意,@Aspect在aspectjweaver 這個jar包裡面,使用idea生成spring項目時沒有出現,需要自己去下載加入.
/**
* 該類聲明為一個切麵,需要把該類放在aop容器當中,再聲明為一個切麵
*/
@Aspect
@Component
public class LoggingAspect {
/***
* 聲明該方法為一個前置通知
*/
@Before("execution(public int com.springtest.aop.CalculationLoggingImpl.add(int,int))")
public void beforeMethod(JoinPoint point){
//獲取當前方法名
String methodName = point.getSignature().getName();
//獲取當前方法的參數列表
List<Object> args = Arrays.asList(point.getArgs());
System.out.println("this is before logging...");
System.out.println("this is method "+methodName+" params is " +args);
System.out.println("this is before logging...");
}
}
簡單配置文件 如下:
<?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" 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">
<!--配置自動掃描的包-->
<context:component-scan base-package="com.springtest.aop"></context:component-scan>
<!--使AspectJ註解起作用,自動為匹配的類生成代理對象-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
Test代碼
//3.使用日誌切麵
//3.1 創建springIOC容器
ApplicationContext cxt = new ClassPathXmlApplicationContext("applicationContext-aop.xml");
//3.2 從IOC容器中獲取bean
Calculation bean = cxt.getBean(Calculation.class);
//3.3 使用bean
System.out.println(bean.add(1,2));
實現結果:
this is before logging...
this is method add params is [1, 2]
this is before logging...
3
可以看到,已經使用loggingAspect切麵將log日誌信息加在了add方法執行之前.
將@before替換為@after,即變更為後置通知,無論是否出現異常,後置通知都會執行.
將@before替換為@AfterReturning,變更為方法結束後通知.在方法正常結束後執行.
@AfterThrowing拋出異常後通知,在方法拋出異常後執行,可以訪問到方法拋出的異常.
@around 環繞通知,需要攜帶ProceddingJoinpoint類型的參數,類似於動態代理實現的過程.ProceddingJoinpoint類型的參數可以決定是否執行目標方法,環繞通知必須要有返回值,沒有返回值會報錯,如下代碼:
@Around("execution(public int com.springtest.aop.CalculationLoggingImpl.add(int,int))")
public void aroundMethod(ProceedingJoinPoint point) {
try {
//獲取當前方法名
String methodName = point.getSignature().getName();
//獲取當前方法的參數列表
List<Object> args = Arrays.asList(point.getArgs());
System.out.println("this is around loggingbegin...");
System.out.println("this is method " + methodName + " params is " + args);
Object result = point.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
System.out.println("this is around loggingend...");
}
沒有返回值,控制台列印如下:
this is around loggingbegin...
Exception in thread "main" org.springframework.aop.AopInvocationException: Null return value from advice does not match primitive return type for: public abstract int com.springtest.aop.Calculation.add(int,int)
this is method add params is [1, 2]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:227)
this is around loggingend...
at com.sun.proxy.$Proxy8.add(Unknown Source)
at com.springtest.aop.Test.main(Test.java:24)
Process finished with exit code 1
表明沒有返回值,加上返回值之後,不再報錯.
另外需要註意的幾點:
1.當有多個切麵同時使用時,可以使用@order標簽來指定優先順序;
2. 切麵表達式是可以重用的,定義一個方法,用於聲明切麵表達式,一般該方法內部不需要再寫任何實現代碼,使用@Pointcut來聲明切入點表達式.格式如下:
/**
* 定義一個方法,用於聲明切入點表達式,不需要在方法內部再加入其它代碼
*/
@Pointcut("execution(public int com.springtest.aop.Calculation.*(int, int))")
public void declarePointCutExpressionEP(){}
@Around(value ="declarePointCutExpressionEP()")
public Object aroundMethod(ProceedingJoinPoint point) {...}
註意:這裡可能會報錯:error at ::0 can't find referenced pointcut declarePointCutExpressionEP,經查證,是因為Aspectweaver這個jar包版本的問題,我使用jdk1.8,最初 使用aspectjweaver-1.6.2.jar,報這個錯誤,更換為aspectjweaver-1.9.2.jar之後,錯誤消失.
總結一下,這篇文章詳細介紹了spring框架的bean工廠的實現以及aop的簡單實現和AspectJ框架的運用.想要熟練運用spring,在面試中不是簡單的背記敘述aop的原理,這些基本的東西是要過一遍的,並且掌握它的原理.
俗話說"好記性不如爛筆頭",在IT行業里,不能只是一味去看視頻,看書,而是要在聽說看的同時,多寫代碼.有的時候,比較難理解的原理,其實寫一個簡單的helloworld的demo就可以幫助自己快速掌握和回顧,與諸君共勉.