JavaWeb学习之Spring框架(一)
Spring負(fù)責(zé)管理項目中的所有對象,Spring看作是項目中對象的管家
Spring框架的功能:aop支持、ioc思想、spring jdbc、aop事務(wù)、junit測試支持
Spring搭建:
導(dǎo)包:beans、context、core、exception四個基礎(chǔ)包
??????apache日志包
創(chuàng)建實體類對象
書寫配置文件:建議文件名為applicationContext.xml
??????導(dǎo)入約束文件Schema約束
代碼測試:1、創(chuàng)建容器對象
????ApplicationContext ac=new ClassPathXmlApplicationContext(“applicationContext.xml”);
2、從容器中獲得實體對象
????????User ?user=(User)ac.getBean(“User”); ??
3、打印該對象
????????System.out.println(user);
Spring思想:
ioc:反轉(zhuǎn)控制
???反轉(zhuǎn)控制就是創(chuàng)建對象的方式反轉(zhuǎn)了。以前對象的創(chuàng)建由開發(fā)人員自己維護(hù),包括依賴關(guān)系也是自己注入;使用spring之后,對象的創(chuàng)建以及以來關(guān)系可以由spring完成創(chuàng)建以及注入。
???反轉(zhuǎn)控制就是反轉(zhuǎn)了對象的創(chuàng)建方式。從我們自己創(chuàng)建反轉(zhuǎn)給了程序
di:依賴注入(注入就是賦值)
??實現(xiàn)ioc思想需要di做支持
??注入的方式:set方法注入、構(gòu)造方法注入、字段注入
??注入的類型:值類型注入---8大基本數(shù)據(jù)類型
??????????????引用類型注入---將依賴對象注入
ApplicationContext&BeanFactory
???BeanFactory接口:spring原始接口,針對原始接口的實現(xiàn)類功能較為單一
?????????????BeanFactory接口實現(xiàn)類的容器,特點是每次在獲得對象時才會創(chuàng)建對象
??ApplicationContext:每次容器啟動時就創(chuàng)建容器中配置的所有對象,并提供更多的功能
????????從類路徑下加載配置文件:ClassPathXmlApplicatiionContext
?????從硬盤絕對路徑下加載配置文件:FileSystemXmlApplicationContext(d:/aaa/ddd/fff)
?????總結(jié):在web開發(fā)中,使用applicationContext,在資源匱乏時使用BeanFactory。
Spring配置文件詳解:
?????Bean元素:
????????將User對象交給spring容器管理
????????Bean元素:使用該元素描述需要spring容器管理的對象
???????????Class屬性:被管理對象的完整類名
???????????name屬性:給被管理的對象起個名字。獲得對象時根據(jù)該名稱獲得對象,可以重復(fù),可以使用特殊字符(盡量使用name屬性)
???????????id屬性:與name屬性一模一樣,但是名稱不可重復(fù),不能使用特殊字符
??????Spring創(chuàng)建對象的方式:
???????????空參構(gòu)造方式:<bean ?name=”user”??class=”com.domain.User”></bean>
?????Bean元素進(jìn)階:
????????Scope屬性
???????????Singleton(默認(rèn)值):單例對象,被標(biāo)識為單例的對象在spring容器中只會存在一個實例
???????????Prototype:多例原型,被標(biāo)識為多例的對象,每次再獲得再會創(chuàng)建,每次創(chuàng)建都是新的對象。
???????Spring的分模塊配置
????????<!--導(dǎo)入其他spring配置文件-->
????????<import ?resource=”com.domain/applicationContext.xml”/>
Spring屬性注入:
??Set方法注入
??構(gòu)造函數(shù)注入
??復(fù)雜類型注入(數(shù)組、list、map、properties)
?
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://www.springframework.org/schema/beans"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd "><!-- 將User對象交給Spring容器來管理 --><!-- 通過set方法進(jìn)行注入 --><bean name="user" class="com.domain.User"><!-- 值注入,也就是變量賦值 --><property name="name" value="張三"></property><property name="age" value="18"></property><!-- 引用類型注入 --><property name="car" ref="car"></property></bean><bean name="car" class="com.domain.Car"><!-- 值注入 --><property name="cname" value="蘭博基尼"></property><property name="color" value="黃色"></property></bean><!-- 通過構(gòu)造方法進(jìn)行注入 --><bean name="user1" class="com.domain.User"><constructor-arg name="name" value="8" index="0" type="java.lang.Integer"></constructor-arg><constructor-arg name="car" ref="car" index="1"></constructor-arg></bean> </beans>?
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://www.springframework.org/schema/beans"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd "><!-- 通過set方法進(jìn)行注入 --><bean name="user" class="com.domain.User"><!-- 值注入,也就是變量賦值 --><property name="name" value="張三"></property><property name="age" value="18"></property><!-- 引用類型注入 --><property name="car" ref="car"></property></bean><bean name="car" class="com.domain.Car"><!-- 值注入 --><property name="cname" value="蘭博基尼"></property><property name="color" value="黃色"></property></bean><bean name="cd" class="com.collection.CollectionDemo"><!-- 數(shù)組 --><property name="arr"><array><!-- 值注入 --><value>張三</value><value>李四</value><!-- 引用注入 --><ref bean="user" /></array></property><!-- List集合 --><property name="list"><list><value>孫悟空</value><value>豬八戒</value><ref bean="car" /></list></property><!-- Map類型注入 --><property name="map"><map><entry key="123" value="asd"></entry><entry key="user" value-ref="car"></entry><entry key-ref="user" value-ref="car"></entry></map></property><!-- properties類型注入 --><property name="prop"><props><prop key="driver">123</prop><prop key="username">root</prop><prop key="password">123456</prop></props></property></bean></beans>
?
?
package com.collection;import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set;import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;import com.domain.User;public class Demo {@Testpublic void method1() {// 1.得到容器對象ApplicationContext ac = new ClassPathXmlApplicationContext("com/collection/applicationContext.xml");// 2.管容器要一個對象CollectionDemo cd = (CollectionDemo) ac.getBean("cd");Object[] obj = cd.getArr();for (Object o : obj) {System.out.println(o);}}@Testpublic void method2() {// 1.得到容器對象ApplicationContext ac = new ClassPathXmlApplicationContext("com/collection/applicationContext.xml");// 2.管容器要一個對象CollectionDemo cd = (CollectionDemo) ac.getBean("cd");// 管對象要一個listList list = cd.getList();for (int i = 0; i < list.size(); i++) {System.out.println(list.get(i));}}@Testpublic void method3() {// 1.得到容器對象ApplicationContext ac = new ClassPathXmlApplicationContext("com/collection/applicationContext.xml");// 2.管容器要一個對象CollectionDemo cd = (CollectionDemo) ac.getBean("cd");// 管對象要一個mapMap map = cd.getMap();Set set = map.entrySet();Iterator<Map.Entry> it = set.iterator();while (it.hasNext()) {Map.Entry m = it.next();System.out.println(m.getKey() + "---" + m.getValue());}}@Testpublic void method4() {// 1.得到容器對象ApplicationContext ac = new ClassPathXmlApplicationContext("com/collection/applicationContext.xml");// 2.管容器要一個對象CollectionDemo cd = (CollectionDemo) ac.getBean("cd");// 管對象要一個propertiesProperties prop = cd.getProp();Set<String> set = prop.stringPropertyNames();for (String str : set) {System.out.println(str + "--" + prop.getProperty(str));}} }?
?
使用注解配置spring
1、為主配置文件引入新的命名空間(約束)
2、開啟使用注解代理配置文件
3、在類中使用注解完成配置
將對象注入到容器
@Component(“user”)
??@Service(“user”) ?//service層
??@Controller(“user”) ?//web層
??@Repository(“user”) ?//dao層
修改對象的作用范圍
@Scope(scopeName=”prototype”)
值類型注入:@Value(“tom”)
????????????Private ?String ?name;//通過反射的Field賦值,破壞了封裝性
????????????@Value(“tom”)
????????????Public void ?setName(String ?name){
???????????This.name=name;
}//通過set方法賦值,推薦使用
引用類型注入:@Autowired//自動裝配
??????????@Qualifier(“car”)//使用@Qualifier注解告訴spring容器自動裝配哪個名稱的對象
??????????????Private ?Car ?car; ?//兩個配置使用
初始化|銷毀方法
@PostConstruct ?//在對象被創(chuàng)建后調(diào)用,init-method
@PreDestory ??//在銷毀之前調(diào)用,destory-method
?
Spring與Junit整合測試:
?
???導(dǎo)包:基礎(chǔ)包4個和日志包兩個+aop+test
?
???配置注解:@RunWith(SpringJunit4ClassRunner.class)//幫我們創(chuàng)建容器
?
????????????@ContextConfiguration(“classpath:applicationContext.xml”)//指定創(chuàng)建容器時使用哪個配置文件
?
???測試
?
package com.service;//目標(biāo)對象(UserService被代理的對象) public class UserService {public void add() {System.out.println("這是新增的方法");}public void delete() {System.out.println("這是刪除的方法");}public void update() {System.out.println("這是更新的方法");}public void find() {System.out.println("這是查找的方法");} }?
package com.service;//spring與Junit的整合,適用于測試 import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import com.domain.User;//創(chuàng)建容器 @RunWith(SpringJUnit4ClassRunner.class) // 指定創(chuàng)建容器時使用哪個配置文件 @ContextConfiguration("classpath:applicationContext.xml") public class Demo01 {@Autowired@Qualifier("userService")private UserService userService;@Testpublic void method() {userService.add();} }
?
?
aop思想
?
?????Spring能夠為容器中管理的對象生成動態(tài)代理對象
?
?????動態(tài)代理(優(yōu)先):被代理的對象必須實現(xiàn)接口,才能產(chǎn)生代理對象,如果沒有,將不能產(chǎn)生動態(tài)代理技術(shù)
?
?????Cglib代理(沒有接口):第三方代理技術(shù),cglib代理。可以對任何類生成代理。代理的原理是對目標(biāo)對象進(jìn)行繼承代理。如果目標(biāo)對象被final修飾,那么該類無法被cglib代理。
?
名詞學(xué)習(xí):
?
?????Joinpoint(連接點):目標(biāo)對象中,所有可以增強(qiáng)的方法
?
?????Pointcut(切入點):目標(biāo)對象,已經(jīng)增強(qiáng)的方法
?
?????Advice(通知/增強(qiáng)):增強(qiáng)的代碼
?
?????Target(目標(biāo)對象):被代理對象
?
?????Weaving(織入):將通知應(yīng)用到切入點的過程
?
?????Proxy(代理):將通知織入到目標(biāo)對象之后,形成代理對象
?
?????Aspect(切面):切入點+通知
?
package com.service;import org.aspectj.lang.ProceedingJoinPoint;//通知 public class MyAdvice {// 前置通知public void before() {System.out.println("這是前置通知");}// 后置通知public void afterReturning() {System.out.println("這是后置通知,在異常的時候不調(diào)用");}// 環(huán)繞通知public Object around(ProceedingJoinPoint pjp) throws Throwable {System.out.println("這是環(huán)繞通知之前的部分");Object proceed = pjp.proceed();System.out.println("這是環(huán)繞通知之后的部分");return proceed;}// 異常通知public void afterException() {System.out.println("這是異常通知,在出現(xiàn)異常的時候調(diào)用");}// 后置通知public void after() {System.out.println("后置通知,在出現(xiàn)異常的時候調(diào)用");} }?
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd "><!-- 配置目標(biāo)對象 --><bean name="userService" class="com.service.UserService"></bean><!-- 配置通知 --><bean name="myAdvice" class="com.service.MyAdvice"></bean><!-- 配置切入點 --><aop:config><aop:pointcut expression="execution(* com.service.*Service.*(..))" id="pc"/><aop:aspect ref="myAdvice"><aop:before method="before" pointcut-ref="pc"/><aop:after-returning method="afterReturning" pointcut-ref="pc"/><aop:around method="around" pointcut-ref="pc"/><aop:after-throwing method="afterException" pointcut-ref="pc"/><aop:after method="after" pointcut-ref="pc"/></aop:aspect></aop:config> </beans>
?
轉(zhuǎn)載于:https://www.cnblogs.com/Java-125/p/9178591.html
總結(jié)
以上是生活随笔為你收集整理的JavaWeb学习之Spring框架(一)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 盒子与小球之二
- 下一篇: 源哥每日一题第十七弹 poj 1568