Java全棧工程師帶你玩轉(zhuǎn)SSH框架—spring(二)

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è)的聚集地八毯。"

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末搓侄,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子话速,更是在濱河造成了極大的恐慌讶踪,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,402評論 6 499
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件泊交,死亡現(xiàn)場離奇詭異乳讥,居然都是意外死亡柱查,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,377評論 3 392
  • 文/潘曉璐 我一進店門云石,熙熙樓的掌柜王于貴愁眉苦臉地迎上來唉工,“玉大人,你說我怎么就攤上這事汹忠×芟酰” “怎么了?”我有些...
    開封第一講書人閱讀 162,483評論 0 353
  • 文/不壞的土叔 我叫張陵宽菜,是天一觀的道長谣膳。 經(jīng)常有香客問我,道長赋焕,這世上最難降的妖魔是什么参歹? 我笑而不...
    開封第一講書人閱讀 58,165評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮隆判,結(jié)果婚禮上犬庇,老公的妹妹穿的比我還像新娘。我一直安慰自己侨嘀,他們只是感情好臭挽,可當(dāng)我...
    茶點故事閱讀 67,176評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著咬腕,像睡著了一般欢峰。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上涨共,一...
    開封第一講書人閱讀 51,146評論 1 297
  • 那天纽帖,我揣著相機與錄音,去河邊找鬼举反。 笑死懊直,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的火鼻。 我是一名探鬼主播室囊,決...
    沈念sama閱讀 40,032評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼魁索!你這毒婦竟也來了融撞?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,896評論 0 274
  • 序言:老撾萬榮一對情侶失蹤粗蔚,失蹤者是張志新(化名)和其女友劉穎尝偎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體鹏控,經(jīng)...
    沈念sama閱讀 45,311評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡致扯,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,536評論 2 332
  • 正文 我和宋清朗相戀三年趁窃,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片急前。...
    茶點故事閱讀 39,696評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡醒陆,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出裆针,到底是詐尸還是另有隱情刨摩,我是刑警寧澤,帶...
    沈念sama閱讀 35,413評論 5 343
  • 正文 年R本政府宣布世吨,位于F島的核電站澡刹,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏耘婚。R本人自食惡果不足惜罢浇,卻給世界環(huán)境...
    茶點故事閱讀 41,008評論 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望沐祷。 院中可真熱鬧嚷闭,春花似錦、人聲如沸赖临。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽兢榨。三九已至嗅榕,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間吵聪,已是汗流浹背凌那。 一陣腳步聲響...
    開封第一講書人閱讀 32,815評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留吟逝,地道東北人帽蝶。 一個月前我還...
    沈念sama閱讀 47,698評論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像澎办,于是被迫代替她去往敵國和親嘲碱。 傳聞我的和親對象是個殘疾皇子金砍,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,592評論 2 353

推薦閱讀更多精彩內(nèi)容

  • 通過之前的兩篇我們能在本地搭建單一和集群兩種方式的dubbo服務(wù)局蚀,這篇我們來看 springmvc+spring+...
    安琪拉_4b7e閱讀 2,159評論 0 6
  • ?著作權(quán)歸作者所有:來自51CTO博客作者優(yōu)秀android的原創(chuàng)作品,如需轉(zhuǎn)載恕稠,請注明出處琅绅,否則將追究法律責(zé)任 ...
    傳奇內(nèi)服號閱讀 1,071評論 0 9
  • 1.有追索權(quán)保理看責(zé)任 有追索權(quán)保理,是指保理商不承擔(dān)為債務(wù)人核定信用額度和提供壞賬擔(dān)保的義務(wù)鹅巍,僅提供包括融資在內(nèi)...
    別枝月閱讀 763評論 0 1
  • 原以為自己是個主動思考問題的人千扶,今天再次看到自己的思維其實非常懶惰料祠,看問題總是停留在自己可以看到的位置,...
    盛世贏家葉小華閱讀 158評論 0 0
  • 偶爾 路過擁抱的啜泣 孤獨的哽咽 時常 見她們喜上眉梢 鮮花盛放 對手抓餅的執(zhí)念澎羞,我是從高中帶到大學(xué)的髓绽。記得高三時...
    帥氣的高大爺閱讀 578評論 0 0