spring框架 多種注入方法+註釋實現IOC AOP
一,多種方式實現依賴注入 1.構造注入 構造注入是一種高內聚的體現,特別是針對有些屬性需要在物件在建立時候賦值,且後續不允許修改(不提供setter方法)
<bean id="demo3" class="com.bdqn.cn.Demo"> <constructor-arg><value type="java.lang.String">哈辛</value></constructor-arg> <constructor-arg><value type="int">3</value></constructor-arg> </bean>
2.設值注入:通過setter訪問器注入資料。 設值注入的優劣勢:設值注入使用靈活,但時效性不足,並且大量的setter訪問器增加了類的複雜性。
<bean id="author" class="com.bdqn.cn.Author"> <property name="name" value="夏洛特"/> <property name="age" value="31"/> <property name="sex" value="女"/> </bean> <bean id="book" class="com.bdqn.cn.Book"> <property name="name" value="簡愛"/> <property name="author" ref="author"/> </bean>
3.p名稱空間的使用
spring2.5以後,為了簡化setter方法屬性注入,引用p名稱空間的概念,可以將 子元素,簡化為元素屬性配置 !! 使用p名稱空間必須匯入 xmlns:p=“http://www.springframework.org/schema/p”
<bean id="user" class="entity.User" p:id="1" p:password="123" p:username="zhangsan"/>
二,處理不同型別的資料:特殊字串處理 JavaBean List Array Set Map Properties 空字串 null值
實體類 :TestEntity
package com.bdqn.cn;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
public class TestEntity {
private String specialCharacter1; // 特殊字元值1
private String specialCharacter2; // 特殊字元值2
private User innerBean; // JavaBean型別
private List<String> list; // List型別
private String[] array; // 陣列型別
private Set<String> set; // Set型別
private Map<String, String> map; // Map型別
private Properties props; // Properties型別
private String emptyValue; // 注入空字串值
private String nullValue = "init value"; // 注入null值
public void setSpecialCharacter1(String specialCharacter1) {
this.specialCharacter1 = specialCharacter1;
}
public void setSpecialCharacter2(String specialCharacter2) {
this.specialCharacter2 = specialCharacter2;
}
public void setInnerBean(User user) {
this.innerBean = user;
}
public void setList(List<String> list) {
this.list = list;
}
public void setArray(String[] array) {
this.array = array;
}
public void setSet(Set<String> set) {
this.set = set;
}
public void setMap(Map<String, String> map) {
this.map = map;
}
public void setProps(Properties props) {
this.props = props;
}
public void setEmptyValue(String emptyValue) {
this.emptyValue = emptyValue;
}
public void setNullValue(String nullValue) {
this.nullValue = nullValue;
}
public void showValue() {
System.out.println("特殊字元1:" + this.specialCharacter1);
System.out.println("特殊字元2:" + this.specialCharacter2);
System.out.println("內部Bean:" + this.innerBean.getUsername());
System.out.println("List屬性:" + this.list);
System.out.println("陣列屬性[0]:" + this.array[0]);
System.out.println("Set屬性:" + this.set);
System.out.println("Map屬性:" + this.map);
System.out.println("Properties屬性:" + this.props);
System.out.println("注入空字串:[" + this.emptyValue + "]");
System.out.println("注入null值:" + this.nullValue);
}
}
spring配置檔案:spring_config.xml
<bean id="entity" class="com.bdqn.cn.TestEntity">
<!--使用<![CDATA[]]>標記處理XML特殊字元-->
<property name="specialCharacter1">
<value><![CDATA[P&G]]]></value>
</property>
<!--把XML特殊字元替換為實體引用-->
<property name="specialCharacter2">
<value>P&G</value>
</property>
<!--定義內部Bean-->
<property name="innerBean">
<bean class="com.bdqn.cn.User">
<property name="username">
<value>Mr.Inner</value>
</property>
</bean>
</property>
<!--List型別-->
<property name="list">
<list>
<!--定義List中的元素-->
<value>足球</value>
<value>籃球</value>
</list>
</property>
<!--注入陣列型別-->
<property name="array">
<list>
<value>足球</value>
<value>籃球 </value>
</list>
</property>
<!--Set型別-->
<property name="set">
<set>
<value>足球</value>
<value>籃球 </value>
</set>
</property>
<!--Map型別-->
<property name="map">
<map>
<!--定義Map中的鍵值對-->
<entry>
<key>
<value>football</value>
</key>
<value>足球</value>
</entry>
<entry>
<key>
<value>basketball</value>
</key>
<value>籃球</value>
</entry>
</map>
</property>
<!--注入Properties型別-->
<property name="props">
<props>
<!--定義Properties中的鍵值對-->
<prop key="football">足球</prop>
<prop key="basketball">籃球</prop>
</props>
</property>
<!--注入空字串值-->
<property name="emptyValue">
<value></value>
</property>
<!--注入null值-->
<property name="nullValue">
<null/>
</property>
</bean>
測試類
@Test
public void testEntity(){
ApplicationContext context = new ClassPathXmlApplicationContext("spring_config.xml");
TestEntity testEntity = (TestEntity)context.getBean("entity");
System.out.println(testEntity.toString());
}
}
三 ,使用註解實現IoC的配置 之前我們配置IOC(控制反轉)都是在xml中配置,現在通過註解配置IOC會減少很多程式碼
使用註解實現Bean元件的定義:
(1)@Component:該註解與等效。
(2)@Respository:該註解用於標註Dao類。
(3)@Service:該註解用於標註業務邏輯類。
(4)@Controller:該註解用於標註控制器類。
使用註解實現Bean元件的裝配:
(1)@Autowired:該註解用於注入所依賴的物件。
(2)@Autowired 採用按型別匹配的方式為屬性自動裝配合適的依賴物件,即容器會查詢和屬性型別相匹配的Bean元件,並自動為屬性注入。
(3)@Qualifier:該註解用於指定所需Bean的名字。
載入註解定義的Bean:
首先在spring配置檔案中新增對context名稱空間的宣告,然後使用context名稱空間下的component-scan標籤掃描註解標註的類,base-package 屬性指定了需要掃描的基準包。
實現IOC註解 配置 spring_zhujie.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: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">
<!--多個包逗號隔開-->
<context:component-scan base-package="com.bdqn.dao,com.bdqn.service"/>
</beans>
資料訪問層:userDaoImpl.java
package com.bdqn.dao;
public interface UserDao {
//通過使用者名稱得到密碼
public String getPwd(String name);
}
業務邏輯層:userServiceImpl.java
package com.bdqn.dao.daoimpl;
import com.bdqn.dao.UserDao;
import org.springframework.stereotype.Repository:
@Repository("userDao")
public class UserDaoImpl implements UserDao {
@Override
public String getPwd(String name) {
//忽略資料庫操作
return "admin";
}
}
業務邏輯層:userServiceImpl.java
package com.bdqn.service.serviceimpl;
import com.bdqn.dao.UserDao;
import com.bdqn.service.UserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service("userService")
public class UserServiceImpl implements UserService {
// @Autowired
//@Qualifier("userDao")
private UserDao userDao;
@Override
public String getPwd(String name) {
return userDao.getPwd(name);
}
}
測試類
@Test
public void testzhujie(){
ApplicationContext context=new ClassPathXmlApplicationContext("spring_zhujie.xml");
UserService userService= (UserService) context.getBean("userService");
String pwd= userService.getPwd("admin");
System.out.println(pwd);
}
四 、使用註解定義切面
使用註解實現一個簡單的AOP切面:
spring配置檔案:springConfig.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: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/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<aop:aspectj-autoproxy/>
<bean id="target" class="com.bdqn.aop.Target"></bean>
<bean id="adviceTarget" class="com.bdqn.aop.AdviceTarget"></bean>
</beans>
目標類 Taget .Java
package com.bdqn.aop;
import org.springframework.stereotype.Component;
//目標類
@Component("target")
public class Target {
public String show(String name) {
System.out.println("這是目標方法。。。。");
return "hello"+name;
}
}
目標增強類AdviceTaget.java
package com.bdqn.aop;
import org.aopalliance.intercept.Joinpoint;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
/**
* Created by 18054 on 2018/9/25.
*/
//增強類
@Aspect
public class AdviceTarget {
@Before("execution(* com.bdqn.aop.*.*(..))")
public void before(JoinPoint jp){
System.out.println("引數3"+jp.getArgs()+",方法名"+jp.getSignature()+",目標物件:"+jp.getTarget());
}
@After("execution(* com.bdqn.aop.*.*(..))")
public void after(JoinPoint jp){
System.out.println("這是後置增強");
}
@AfterReturning(value = "execution(* com.bdqn.aop.*.*(..))",returning = "value")
public void afterReturn(JoinPoint jp,String value ){
System.out.println("後置帶返回值"+value);
}
@AfterThrowing(value = "execution(* com.bdqn.aop.*.*(..))", throwing = "ex")
public void afterException(JoinPoint jp,Exception ex){
System.out.println("後置帶異常"+ex);
}
@Around("execution(* com.bdqn.aop.*.*(..))")
public void around(ProceedingJoinPoint jp){
String str= (String) jp.getArgs()[0];
if(str.equals("admin")){
//有許可權,可以訪問目標方法
try {
String value= jp.proceed().toString();
System.out.println("返回值"+value);
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}else {
//無許可權
System.out.println("沒有許可權");
//跳轉到登陸頁面
}
}
}
測試類
@Test
public void testTarget() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring_aop.xml");
Target target = (Target) context.getBean("target");
System.out.println(target);
}```