1.1 基于注解的IOC配置
既注解配置和xml配置要實現(xiàn)的功能都是一樣的,都是要降低程序間的耦合.只是配置的形式不一樣.
1.2 環(huán)境搭建
1.2.1 第一步:拷貝必備的jar包
需要多拷貝一個spring-aop-4.2.4.RELEASE.jar
1.2.2 創(chuàng)建xml文件,導(dǎo)入約束
<?xml version="1.0" encoding="UTF-8"?>
<!-- 導(dǎo)入schema
約束的位置在:
..\spring-framework-4.2.4.RELEASE\docs\spring-framework-reference\html\xsd-configuration.html
文件中社裆。
注意:要導(dǎo)入schema約束
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd ">
</beans>
1.2.3 使用@Component注解配置管理的資源
/**
* 客戶的業(yè)務(wù)層實現(xiàn)類
* @author zhy
*
@Component(value="customerService")
public class CustomerServiceImpl implements ICustomerService {
@Override
public void saveCustomer() {
System.out.println("執(zhí)行了保存客戶");
}
}
1.2.4 第四步在spring的配置文件中開啟spring對注解ioc的支持
<!--告知spring框架在,讀取配置文件,創(chuàng)建容器時,掃描注解,依據(jù)注解創(chuàng)建對象,并存入容器中.>
<context:component-scan base-package="com.baidu"></context:component-sacn>
1.3 常用注解
1.3.1 用于創(chuàng)建對象的
相當(dāng)于 : <bean id="" class="">
1.3.1.1 @Component
作用:
把資源讓spring來管理.相當(dāng)于在xml配置一個bean.
屬性:
value: 指定bean的id.如果不指定value屬性,默認bean的id是當(dāng)前類的類名.首字母小寫.
1.31.2 @Controller @Service @Repository
們?nèi)齻€注解都是針對一個的衍生注解磷账,他們的作用及屬性都是一模一樣的暖哨。
他們只不過是提供了更加明確的語義化。
@Controller:一般用于表現(xiàn)層的注解够话。
@Service:一般用于業(yè)務(wù)層的注解禁熏。
@Repository:一般用于持久層的注解。
細節(jié):如果注解中有且只有一個屬性要賦值時左驾,且名稱是value,value在賦值是可以不寫极谊。
1.3.2 用于注入數(shù)據(jù)的
相當(dāng)于 : <property name="" ref=""> 或者 <property name="" value="">
1.3.2.1@Autowired
作用:
自動按照類型注入。當(dāng)使用注解注入屬性時安岂,set方法可以省略轻猖。它只能注入其他bean類型。當(dāng)有多個類型匹配時域那,使用要注入的對象變量名稱作為bean的id咙边,在spring容器查找猜煮,找到了也可以注入成功。找不到就報錯败许。
/**
* @Autowired 自動裝配王带,自動按類型注入對象
* <bean id="userService" class="com.baidu.demo2.UserServiceImpl" scope="" init-method="init">
* <property name="userDao" ref="ud"/>
* </bean>
*
* @Autowired
@Qualifier(value="userDao") 這2個注解必須要一起使用,按id名稱注入
@Resource 是Java提供注解市殷,Spring容器支持該注解愕撰。可以通過name在容器中查找指定名稱的對象
*
1.3.2.2@Qualifier
作用:
在自動按照類型注入的基礎(chǔ)之上醋寝,再按照Bean的id注入搞挣。它在給字段注入時不能獨立使用,必須和@Autowire一起使用音羞;但是給方法參數(shù)注入時囱桨,可以獨立使用。
屬性:
value:指定bean的id嗅绰。
1.3.2.3@Resource
作用:
直接按照Bean的id注入舍肠。它也只能注入其他bean類型。
屬性:
name:指定bean的id窘面。
1.3.2.4@Value
作用:
注入基本數(shù)據(jù)類型和String類型數(shù)據(jù)的
屬性:
value:用于指定值
1.3.3用于改變作用范圍的:
相當(dāng)于:<bean id="" class="" scope="">
1.3.3.1@Scope
作用:
指定bean的作用范圍翠语。
屬性:
value:指定范圍的值。
取值:singleton prototype request session globalsession
1.3.4和生命周期相關(guān)的:(了解)
相當(dāng)于:<bean id="" class="" init-method="" destroy-method="" />
1.3.4.1@PostConstruct
作用:
用于指定初始化方法民镜。
1.3.4.2@PreDestroy
作用:
用于指定銷毀方法啡专。
1.3.5代碼示例
業(yè)務(wù)層代碼:
/**
* 客戶的業(yè)務(wù)層接口
*/
public interface ICustomerService {
/**
* 保存客戶
* @param customer
*/
void saveCustomer();
}
/**
* 客戶的業(yè)務(wù)層實現(xiàn)類
*/
//作用就相當(dāng)于在xml中配置了一個bean標(biāo)簽,該注解有value屬性制圈,含義是bean的id们童。
//不寫的時候,默認的id是:當(dāng)前類名鲸鹦,且首字母小寫慧库。即:customerServiceImpl
@Component(value="customerService")
@Scope(value="singleton")
public class CustomerServiceImpl implements ICustomerService {
// @Autowired
// 自動按照數(shù)據(jù)類型注入,拿著當(dāng)前變量的數(shù)據(jù)類型在spring的容器中找馋嗜,找到后齐板,給變量賦值。
// 當(dāng)有多個類型匹配時葛菇,會使用當(dāng)前變量名稱customerDao作為bean的id甘磨,繼續(xù)在容器中找。
// 找到了眯停,也能注入成功济舆。找不到就報錯。
// @Qualifier(value="customerDao2")//在自動按照類型注入的基礎(chǔ)之上莺债,再按照id注入
@Resource(name="customerDao2")//直接按照bean的id注入
private ICustomerDao customerDao = null;
@Value("com.mysql.jdbc.Driver")//注入基本類型和String類型數(shù)據(jù)
private String driver;
@Override
public void saveCustomer() {
System.out.println(driver);
customerDao.saveCustomer();
}
}
持久層代碼:
/**
* 客戶的持久層接口
*/
public interface ICustomerDao {
/**
* 保存客戶
*/
void saveCustomer();
}
/**
* 客戶的持久層實現(xiàn)類11111111111111111111
*/
@Repository("customerDao1")
public class CustomerDaoImpl implements ICustomerDao {
@Override
public void saveCustomer() {
System.out.println("保存了客戶111111111111111111");
}
}
/**
* 客戶的持久層實現(xiàn)類222222222222222222222222
*/
@Repository("customerDao2")
public class CustomerDaoImpl2 implements ICustomerDao {
@Override
public void saveCustomer() {
System.out.println("保存了客戶2222222222222222222");
}
}
測試類代碼:
public class Client {
public static void main(String[] args) {
//1.獲取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根據(jù)id獲取對象
ICustomerService cs = (ICustomerService) ac.getBean("customerService"); cs.saveCustomer();
}
}
配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<!-- 我們導(dǎo)入約束時滋觉,除了昨天的那部分之外签夭,還要單獨導(dǎo)入一個context名稱空間 -->
<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"
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">
<!-- 告知spring框架在通過讀取配置文件創(chuàng)建容器時,掃描的包椎侠,并根據(jù)包中類的注解創(chuàng)建對象-->
<context:component-scan base-package="com.baidu"></context:component-scan>
</beans>
1.3.6 關(guān)于Spring注解和XML的選擇問題
注解的優(yōu)勢 :
配置簡單,維護方便(我們找到類,就相當(dāng)于找到了對應(yīng)的配置)
XML的優(yōu)勢 :
修改時,不用改源碼.不涉及重寫編譯和部署.
Spring管理Bean方式的比較 :
基于XML配置 基于注解配置
Bean定義 <bean id="..." class=".."> @Component 衍生類@Repository @Service @Controller
Bean名稱 通過id或name指定 @Component("person")
Bean注入 <property>或者通過p命名空間 @Autowired按類型注入 @Qualifier按名稱注入
生命過程, init-method destroy-method @PostConstruct初始化 @PreDestroy銷毀 @Scope設(shè)置作用范圍
Bean作用范圍 范圍scope屬性
適合場景 Bean來自第三方,使用其它 Bean的實現(xiàn)類由用戶自己開發(fā)
1.5 spring的純注解配置
/**
* 客戶的業(yè)務(wù)層實現(xiàn)類
*/
@Configuration//表明當(dāng)前類是一個配置類
@ComponentScan(basePackages = "com.baidu")//配置要掃描的包
public class SpringConfiguration {
}
那么新的問題又來了第租,我們?nèi)绾潍@取容器呢?
public class Client {
public static void main(String[] args) {
//1.獲取容器:由于我們已經(jīng)沒有了xml文件我纪,所以再用讀取xml方式就不能用了慎宾。
//這時需要指定加載哪個類上的注解
ApplicationContext ac =
new AnnotationConfigApplicationContext(SpringConfiguration.class);
//2.根據(jù)id獲取對象
ICustomerService cs = (ICustomerService) ac.getBean("customerService");
cs.saveCustomer();
}
}
1.5.3新注解說明
1.5.3.1@Configuration
作用:
用于指定當(dāng)前類是一個spring配置類,當(dāng)創(chuàng)建容器時會從該類上加載注解宣羊。獲取容器時需要使用AnnotationApplicationContext(有@Configuration注解的類.class)璧诵。
屬性:
value:用于指定配置類的字節(jié)碼
示例代碼:
/**
* 用于初始化spring容器的配置類
*/
@Configuration
public class SpringConfiguration{
}
1.5.3.2@ComponentScan
作用:
用于指定spring在初始化容器時要掃描的包。作用和在spring的xml配置文件中的:
<context:component-scan base-package="com.baidu"/>是一樣的仇冯。
屬性:
basePackages:用于指定要掃描的包之宿。和該注解中的value屬性作用一樣。
1.5.3.4@Import
作用:
用于導(dǎo)入其他配置類苛坚,在引入其他配置類時比被,可以不用再寫@Configuration注解。當(dāng)然泼舱,寫上也沒問題等缀。
屬性:
value[]:用于指定其他配置類的字節(jié)碼。
示例代碼:
@Configuration
@ComponentScan(basePackages = "cn.baidu.spring")
@Import({ Configuration_B.class})
public class Configuration_A {
}
@Configuration
@PropertySource("classpath:info.properties")
public class Configuration_B {
}
1.5.3.5@Bean
作用:
該注解只能寫在方法上娇昙,表明使用此方法創(chuàng)建一個對象尺迂,并且放入spring容器。它就相當(dāng)于我們之前在xml配置中介紹的factory-bean和factory-method冒掌。
屬性:
name:給當(dāng)前@Bean注解方法創(chuàng)建的對象指定一個名稱(即bean的id)噪裕。
示例代碼:
@Bean(name = "datasource2")
public DataSource createDS() throws Exception {
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
comboPooledDataSource.setUser("root");
comboPooledDataSource.setPassword("1234");
comboPooledDataSource.setDriverClass("com.mysql.jdbc.Driver");
comboPooledDataSource.setJdbcUrl("jdbc:mysql:///spring_ioc");
return comboPooledDataSource;
}
單元整合
/**
* Spring整合Junit單元測試
* @author Administrator
*/
@RunWith(value=SpringJUnit4ClassRunner.class)
@ContextConfiguration(value="classpath:applicationContext.xml")
public class Demo1 {
// 測試哪個對象,可以使用resource注解把對象注入進來
@Resource(name="userService")
private UserService userService;
@Resource(name="userDao")
private UserDao userDao;
/**
* Spring 整合Juint單元測試的方法
*/
@Test
public void run3(){
userService.save();
}
@Test
public void run4(){
// userService.update();
userDao.save();
}
使用XML方式完成IOC的入門
1. 導(dǎo)入jar包
2. 編寫接口和實現(xiàn)類
3. 編寫配置文件,管理實現(xiàn)類
4. 編寫入門的程序
使用注解的方式完成IOC的入門
1. 導(dǎo)入jar包
2. 編寫接口和實現(xiàn)類
3. 編寫applicationContext.xml配置文件,目的 : 讓注解生效
4. 在實現(xiàn)類上編寫注解
5. 編寫入門的程序
1. 管理類的
@Component 所有類都可以使用
@Controller Web層使用的注解,就是Action使用的.
@Service 業(yè)務(wù)層使用的注解
@Repository 持久層使用的注解
2. 依賴注入的注解 (set方法可以省略不寫)
@Value 給普通類型屬性注入值(String int double)
@Resource 給引用類型注入值的,強調(diào) : 該注解的屬性時name
@Scope 對象作用范圍,默認單例的.
Spring整合WEB
ServletContext對象,服務(wù)器啟動就創(chuàng)建,服務(wù)器關(guān)閉就銷毀.
監(jiān)聽器 : 監(jiān)聽ServletContext域?qū)ο蟮膭?chuàng)建和銷毀的.
ServletContextListener監(jiān)聽器 , init destory
總結(jié) :
服務(wù)器啟動后,Spring創(chuàng)建對象,Spring創(chuàng)建Web版本的工廠,把工廠保存到ServletContext域?qū)ο笾?
編寫 :
從ServletContext對象中獲取到Web版本的工廠,從工廠中獲取到Service對象,調(diào)用方法.
SSH框架之Spring第二篇
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
- 文/潘曉璐 我一進店門宣肚,熙熙樓的掌柜王于貴愁眉苦臉地迎上來毒姨,“玉大人,你說我怎么就攤上這事钉寝』∧牛” “怎么了?”我有些...
- 文/不壞的土叔 我叫張陵嵌纲,是天一觀的道長俘枫。 經(jīng)常有香客問我,道長逮走,這世上最難降的妖魔是什么鸠蚪? 我笑而不...
- 正文 為了忘掉前任,我火速辦了婚禮师溅,結(jié)果婚禮上茅信,老公的妹妹穿的比我還像新娘。我一直安慰自己墓臭,他們只是感情好蘸鲸,可當(dāng)我...
- 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著窿锉,像睡著了一般酌摇。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上嗡载,一...
- 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼挪哄!你這毒婦竟也來了吧秕?” 一聲冷哼從身側(cè)響起,我...
- 正文 年R本政府宣布饼灿,位于F島的核電站幕侠,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏碍彭。R本人自食惡果不足惜晤硕,卻給世界環(huán)境...
- 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望庇忌。 院中可真熱鬧舞箍,春花似錦、人聲如沸皆疹。這莊子的主人今日做“春日...
- 文/蒼蘭香墨 我抬頭看了看天上的太陽墙基。三九已至软族,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間残制,已是汗流浹背立砸。 一陣腳步聲響...
推薦閱讀更多精彩內(nèi)容
- 一折汞、ssd整合(spring+struts+jdbc) 步驟: 導(dǎo)入入struts+spring整合需要的jar文...