1.Spring 中的 bean 管理(注解方式)
1.1 使用注解創(chuàng)建對象Spring 創(chuàng)建對象可以使用配置 xml 文件的方式卤材,也可以使用注解來創(chuàng)建對象浆兰,更加的簡單愿吹。這就需要另外引入一個 spring-aop 的 jar 包躬厌,還要在配置文件中加上相對應(yīng)的約束牙甫。
示例代碼如下:
實體類
加上注解滩褥,@Component(value="student") 注解就相當(dāng)于之前用配置 <bean id="student" class="..."/>
創(chuàng)建對象有四個注解病蛉,另外三個注解 @controller,@Service瑰煎,@Repository 都是 @Component 的衍生注解铺然,它們在功能上是一樣的,都是創(chuàng)建對象酒甸。從名稱上也可以看出注解有劃分要標(biāo)注的類的用途魄健,@Component 用于一般的實體類,@controller 用于 Web 層插勤,@Service 用于 業(yè)務(wù)邏輯層沽瘦,@Repository 用于數(shù)據(jù)持久層。
另外农尖,創(chuàng)建對象是單實例還是多實例也是可以使用注解析恋,只需要在類上加上 @Scope(value="prototype") 就可以創(chuàng)建多實例的對象。
package cc.wenshixin.entity;
import org.springframework.stereotype.Component;
@Component(value="student")
public class Student {
public void study(){
System.out.println("學(xué)習(xí)中盛卡。助隧。。");
}
}
配置文件
在約束配置要加上 xmlns:context="http://www.springframework.org/schema/context" 和 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd滑沧。
開啟注解掃描并村,可以到包中掃描類、方法滓技、屬性上是否有注解哩牍。
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/context http://www.springframework.org/schema/context/spring-context.xsd">
測試方法
package cc.wenshixin.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cc.wenshixin.entity.Student;
public class Test1 {
@Test
public void test01()
{
//1.加載spring的配置文件,根據(jù)配置文件來創(chuàng)建對象
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
//2.得到通過注解創(chuàng)建的對象
Student s = (Student) context.getBean("student");
s.study();
}
}
1.2 使用注解注入屬性創(chuàng)建 service 類和創(chuàng)建 dao 類令漂,在 service 中得到 dao 類的對象姐叁。
dao 類
package cc.wenshixin.dao;
import org.springframework.stereotype.Repository;
@Repository(value="dao")
public class Dao {
public void insert()
{
System.out.println("插入數(shù)據(jù)。。外潜。");
}
}
service 類
使用注解方式來注入屬性原环,有兩種方式,并且兩種方式都不要需要在 dao 中添加 set 方法处窥。
package cc.wenshixin.service;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cc.wenshixin.dao.Dao;
@Service(value="service")
public class StudentService {
//第一種方式
/*@Autowired
private Dao dao;*/
//第二種方式
//name屬性值寫創(chuàng)建 dao 對象時注解中的 value 值
@Resource(name="dao")
private Dao dao;
public void add()
{
System.out.println("添加操作嘱吗。。滔驾。");
dao.insert();
}
}
測試方法
package cc.wenshixin.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cc.wenshixin.entity.Student;
import cc.wenshixin.service.StudentService;
public class Test1 {
@Test
public void test01()
{
//1.加載spring的配置文件谒麦,根據(jù)配置文件來創(chuàng)建對象
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
//2.得到通過注解創(chuàng)建的對象
StudentService service = (StudentService) context.getBean("service");
service.add();
}
}
1.3 配置方式和注解方式的混合使用在開發(fā)中,經(jīng)常 xml 配置文件方式和注解方式混合使用哆致,創(chuàng)建對象使用配置文件绕德,而屬性注入使用注解方式。xml 配置方式結(jié)構(gòu)清晰摊阀,注解方式方便屬性注入耻蛇。
Spring 中 bean 管理方式的比較
xml配置注解配置bean 定義<bean id="" class=""/>@Component,@Respository胞此,@Service臣咖,@Controllerbean 名稱通過id或者name指定@Component("student"),單個value值漱牵,value可以省略bean 注入<property>或者通過p命名空間@Autowired 按類型注入夺蛇,@Resource(name="")
示例代碼如下:
dao 類
package cc.wenshixin.dao;
public class TeacherDao {
public void insert()
{
System.out.println("添加老師。酣胀。刁赦。");
}
}
package cc.wenshixin.dao;
public class StudentDao {
public void insert()
{
System.out.println("添加學(xué)生。闻镶。截型。");
}
}
service 類
package cc.wenshixin.service;
import javax.annotation.Resource;
import cc.wenshixin.dao.StudentDao;
import cc.wenshixin.dao.TeacherDao;
public class Service {
@Resource(name="teacherDao")
private TeacherDao teacherDao;
@Resource(name="studentDao")
private StudentDao studentDao;
public void add()
{
System.out.println("添加操作。儒溉。宦焦。");
teacherDao.insert();
studentDao.insert();
}
}
配置文件
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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/context http://www.springframework.org/schema/context/spring-context.xsd">
測試方法
package cc.wenshixin.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cc.wenshixin.service.Service;
public class Test1 {
@Test
public void test()
{
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
Service service = (Service) context.getBean("service");
service.add();
}
}
2.Spring 中的 AOP
2.1 AOP 完整概述AOP,全名 Aspect Oriented Programming顿涣,面向切面編程波闹,在 Struts2 的攔截器中已經(jīng)提到過 AOP,時通過預(yù)編譯方式和運行期動態(tài)代理實現(xiàn)程序功能的統(tǒng)一維護的一種技術(shù)涛碑,擴展功能而不修改源代碼精堕,如:權(quán)限校驗、日志記錄蒲障、性能監(jiān)控歹篓、事務(wù)控制瘫证。AOP采取橫向抽取機制,取代了傳統(tǒng)縱向繼承體系的重復(fù)代碼庄撮。AOP 解決 OOP(面向?qū)ο缶幊蹋?中遇到的一些問題背捌,是 OOP 的延續(xù)和擴展。
底層的動態(tài)代理機制有兩種:
有接口洞斯,JDK的動態(tài)代理毡庆,針對實現(xiàn)接口的類產(chǎn)生代理,生成接口實現(xiàn)類對象烙如。
沒有接口么抗,Cglib的動態(tài)代理,應(yīng)用的是底層的字節(jié)碼增強技術(shù)亚铁,生成當(dāng)前類的子類對象蝇刀。
2.2 AOP 的底層原理
縱向抽取機制
橫向抽取機制
2.3 AOP 操作的相關(guān)術(shù)語
Joinpoint(連接點):類里面可以被增強的方法,這些方法就稱為是連接點徘溢。
Pointcut(切入點):切入點是指要對連接點進行攔截吞琐。在一個類里面可以有很多的方法被增強,比如實際操作中甸昏,只是增強了類里面的 add 方法和 update 方法,實際增強的方法就稱為是切入點徐许。
Advice(通知/增強):通知是指攔截到 Joinpoint 之后要做的事情就是通知施蜜,通知又分為前置通知、后置通知雌隅、異常通知翻默,最終通知、環(huán)繞通知(切面要完成的功能)恰起。要增強的邏輯功能稱為是增強修械,比如擴展日志功能,這個日志功能就成為是通知或者是增強检盼。前置通知:在增強的方法之前執(zhí)行肯污;后置通知:在增強的方法之后執(zhí)行;異常通知:方法出現(xiàn)異常時吨枉;最終通知:在后置之后執(zhí)行蹦渣;環(huán)繞通知:在方法之前和之后執(zhí)行。
Aspect(切面):切入點和通知(引介)的結(jié)合貌亭。把增強應(yīng)用到具體方法上面的過程稱為切面柬唯。把增強用到切入點過程。
Introduction(引介):引介是一種特殊的通知在不修改類代碼的前提下圃庭,Introduction 可以在運行期為類動態(tài)地添加一些方法或 Field锄奢。
Target(目標(biāo)對象):代理的目標(biāo)對象(要增強的類)失晴。
Weaving(織入):是把增強應(yīng)用到目標(biāo)的過程,也即是把 advice 應(yīng)用到 target 的過程拘央。
Proxy(代理):一個類被 AOP 織入增強后就產(chǎn)生一個結(jié)果代理類涂屁。
2.4 AOP 的實際操作
在 Spring 中進行 AOP 操作使用 Aspectj 實現(xiàn)的,Aspectj 不是 Spring 的一部分堪滨,和 Spring 一起使用 AOP 操作胯陋。
使用 Aspectj 實現(xiàn) AOP 也有兩種方式:
1.基于 Aspectj 的xml配置
2.基于 Aspectj 的注解方式
除了上面的 jar 包之外,還需要導(dǎo)入 Aspectj 的相關(guān) jar 包 Aspectjweaver.jar 下載地址袱箱,aopalliance.jar遏乔,這個在 Struts2 的lib中有,spring-aop.jar发笔、spring-aspects.jar盟萨。
2.4.1 配置文件方式
實體類
package cc.wenshixin.entity;
public class Student {
public void study()
{
System.out.println("學(xué)習(xí)中。了讨。捻激。");
}
}
增強類
package cc.wenshixin.entity;
import org.aspectj.lang.ProceedingJoinPoint;
public class StrengthStudent {
public void beforeStudy()
{
System.out.println("前置增強。前计。胞谭。");
}
public void afterStudy()
{
System.out.println("后置增強。男杈。丈屹。");
}
//環(huán)繞通知
public void aroundStudy(ProceedingJoinPoint proceedingJoinPoint) throws Throwable
{
//方法之前執(zhí)行
System.out.println("方法之前。伶棒。旺垒。");
//執(zhí)行被增強的方法
proceedingJoinPoint.proceed();
//方法之后執(zhí)行
System.out.println("方法之后。肤无。先蒋。");
}
}
配置文件
aspectj配置常用的表達式
execution(<訪問修飾符>?<返回類型><方法名>(<參數(shù)>)<異常>)
1.execution(* cc.wenshixin.entity.Student.add(..))
2.execution(* cc.wenshixin.entity.Student.*(..))
3.execution(* *.*(..))
注意:第一個和后面的路徑有一個空格宛渐,后面的括號中是兩個點竞漾,不是三個點*
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">
測試方法
package cc.wenshixin.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cc.wenshixin.entity.Student;
public class Test1 {
@Test
public void test()
{
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
Student s = (Student) context.getBean("student");
s.study();
}
}
2.4.2 注解方式
實體類同上
增強類
Aspectj 的 AOP 注解
@Aspect:定義切面增強類的注解
通知(增強)類型
@Before:前置通知
@AfterReturing:后置通知
@Around:環(huán)繞通知
@AfterThrowing:異常拋出通知
package cc.wenshixin.entity;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class StrengthStudent {
@Before(value="execution(* cc.wenshixin.entity.Student.*(..))")
public void beforeStudy()
{
System.out.println("前置增強。窥翩。畴蹭。");
}
@After(value="execution(* cc.wenshixin.entity.Student.*(..))")
public void afterStudy()
{
System.out.println("后置增強。鳍烁。叨襟。");
}
//環(huán)繞通知
@Around(value="execution(* cc.wenshixin.entity.Student.*(..))")
public void aroundStudy(ProceedingJoinPoint proceedingJoinPoint) throws Throwable
{
//方法之前執(zhí)行
System.out.println("方法之前。幔荒。糊闽。");
//執(zhí)行被增強的方法
proceedingJoinPoint.proceed();
//方法之后執(zhí)行
System.out.println("方法之后梳玫。。右犹。");
}
}
配置文件
<?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">
<!-- 1.配置對象 -->
<bean id="student" class="cc.wenshixin.entity.Student"></bean>
<bean id="strengthStudent" class="cc.wenshixin.entity.StrengthStudent"></bean>
<!-- 2.開啟AOP操作 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
測試方法同上
3. 其他概念
3.1 log4j 的介紹log4j 是一個日志包提澎,通過 log4j 可以看到程序運行過程中更詳細(xì)的信息,查看日志念链。使用時需要導(dǎo)入 log4j 的 jar 包盼忌,下載位置,并復(fù)制 log4j 的配置文件 log4j.properties 到 src 目錄掂墓。
log4j.properties文件中的內(nèi)容
log4j.rootLogger 用來設(shè)置日志的級別谦纱,info可以看到基本信息,debug可以看到更詳細(xì)的信息君编。
#
# Log4J Settings for log4j 1.2.x (via jakarta-commons-logging)
#
# The five logging levels used by Log are (in order):
#
# 1. DEBUG (the least serious)
# 2. INFO
# 3. WARN
# 4. ERROR
# 5. FATAL (the most serious)
# Set root logger level to WARN and append to stdout
log4j.rootLogger=DEBUG, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%d %5p (%c:%L) - %m%n
每天都在分享文章跨嘉,也每天都有人想要我出來給大家分享下怎么去學(xué)習(xí)Java。大家都知道吃嘿,我們是學(xué)Java全棧的祠乃,大家就肯定以為我有全套的Java系統(tǒng)教程。沒錯兑燥,我是有Java全套系統(tǒng)教程亮瓷,進扣裙【47】974【9726】所示,今天小編就免費送!~
后記:對于大部分轉(zhuǎn)行的人來說降瞳,找機會把自己的基礎(chǔ)知識補齊嘱支,邊工作邊補基礎(chǔ)知識,真心很重要力崇《诽粒“我們相信人人都可以成為一個程序員赢织,現(xiàn)在開始亮靴,找個師兄,帶你入門于置,學(xué)習(xí)的路上不再迷茫茧吊。這里是ja+va修真院,初學(xué)者轉(zhuǎn)行到互聯(lián)網(wǎng)行業(yè)的聚集地八毯。"