前言
在之前的博客中,小鹹兒使用xml配置的方式,讓IOC容器實現對象的創建以及依賴的功能。接下來使用另一種更爲簡單的方式——註解
敘述
註解模式
之前小鹹兒已經寫過如何通過xml文件來創建對象,接下來直接說明註解的使用方式。
接口層
首先,需要自己創建一個接口層:UserService
package annotation;
/**
* IOC示例:接口
* @author Phyllis
* @date 2019年7月18日17:35:06
*/
public interface UserService {
/**
* 通過用戶ID查詢用戶信息
* @Param userId
* @return
*/
public void selectByUserId(String userId);
}
實現層
接下來就是需要自己去創建一個具體實現類:UserServiceImpl
package annotation;
import org.springframework.stereotype.Component;
/**
* IOC示例:具體實現類
* @author Phyllis
* @date 2019年7月18日17:36:38
*/
@Component("userServiceId")
public class UserServiceImpl implements UserService {
/**
* 通過用戶ID查詢用戶信息
* @Param userId
* @return
*/
public void selectByUserId(String userId) {
if(userId == '123'){
System.out.println("此用戶不存在");
}
}
}
但是不同的是,這裏需要添加一個註解@Component,引自org.springframework.stereotype.Component。
作用:
@Component 取代 <bean class="">
@Component("id") 取代 <bean id="" class="">
除此之外呢,在web開發中,還提供了3個@Component註解的衍生註解,功能與其一樣,可以取代<bean class="">
使用。在這個實例中使用的上述註解。
@Repository :dao 層
@Service:service 層
@Controller:web 層
xml配置文件
雖然我們使用了註解,但是我們也需要讓程序再啓動時能夠讀取這個註解,這樣才能發揮這個註解的作用,所以還需要在xml配置文件中,寫明需要去掃描那些配置了註解的包
首先需要創建一個beans.xml文件放入到resources中
接着在配置文件中配置好需要掃描的包
<?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:context="http://www.springframework.org/schema/context"
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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--組件掃描,掃描含有註解的類-->
<context:component-scan base-package="annotation"></context:component-scan>
</beans>
測試類
這時候就可以做一個簡單的測試了:TestAnnoIoc
package annotation;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestAnnoIoc {
@Test
public void demo01(){
// 從spring容器中獲得
// 1、獲得容器
String xmlPath = "beans.xml";
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
// 2、獲得內容---不需要自己new,都是從spring容器獲得
UserService userService = (UserService) applicationContext.getBean("userServiceId");
userService.selectByUserId("123");
}
}
結果: 這個實例仍然能夠運行成功,也就是說使用註解+xml配置文件的形式,讓註解去幫助我們創建對象。
其他註解
另外,如果在依賴注入時,需要給私有字段設置或者給setter方法設置,該怎麼辦呢?
接下來就來說明一下,該如何解決:
- 普通值:使用
@Value(“”)
即可 - 引用值:
方式一:按照類型注入:@Autowired
方式二:按照名稱注入1:@Autowired 或者 @Qualifier("名稱")
方式三:按照名稱注入2:@Resources("名稱")
總結
這裏只是一個簡單的註解使用過程,其中有關@Component註解的底層機制,小鹹兒還需要進行深入的學習,接下來會有更多分享。
感謝您的閱讀~~