帶你快速入門掌握Spring的那些注解使用
一、前言
這是spring專欄的第三篇文章,是關于spring的注解開發(fā),包括完全注解和非完全注解開發(fā)。自己整理了學習的筆記,希望大家喜歡。
二、基本介紹
前面兩篇關于spring的知識點學習,我都是用xml配置文件來一步步講解的,但是Spring是輕代碼而重配置的框架,xml配置文件比較繁重,影響開發(fā)效率,所以注解開發(fā)是一種趨勢,注解代替xml配置文件可以簡化配置,提高開發(fā)效率。
因此,我在寫這篇文章之前,一直在思考,如何用一種方式來讓小伙伴們理解的更加深刻呢?最后決定,我在講解注解使用的時候,要與使用xml配置文件的方式進行一個對比,盡量讓小伙伴們知其所以然!
三、非全注解開發(fā)
1、第一組注解
這組注解關于對象的實例化創(chuàng)建,在功能上都沒有區(qū)別
- @Component 使用在類上用于實例化Bean
- @Controller 使用在web層類上用于實例化Bean
- @Service 使用在service層類上用于實例化Bean
- @Repository 使用在dao層類上用于實例化Bean
接下來讓我們從具體的代碼分析,理解和掌握它們吧!
先創(chuàng)建一個UserDao接口,隨便寫一個sayHello()方法
public interface UserDao { void sayHello(); }
然后寫一個接口實現(xiàn)類UserDaoImpl類,實現(xiàn)接口的方法,輸出“大家好,我是卷心菜~~”
//<bean id="userDao" class="com.sht.dao.impl.UserDaoImpl"></bean> @Repository(value = "userDao") public class UserDaoImpl implements UserDao { @Override public void sayHello() { System.out.println("大家好,我是卷心菜~~"); } }
分析: 在類上加上@Repository(value = "userDao")就表示把這個類的實例放進了spring容器中,value = "userDao"就相當于<bean id="userDao" class="com.sht.dao.impl.UserDaoImpl"></bean>中的id屬性值,我們使用注解的時候,就不需要在指定類的包路徑了,因此省略了class屬性值
注意,使用非全注解開發(fā),意味著要配置spring文件,與之前不同的是,我們要在配置文件中加上一個包掃描,才能讓注解生效
<?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" 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"> <!--掃描包及其子包--> <context:component-scan base-package="com.sht"/> </beans>
寫一個測試代碼:
@Test public void test4() { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); UserService userService = applicationContext.getBean(UserService.class); userService.sayHello(); }
運行結果:
2、第二組注解
這一組注解的功能是屬性注入,讓我們寫一個代碼看看他們的使用方法
- @Autowired
- @Resource
- @Qulifier:和@Autowired一起使用
創(chuàng)建一個接口UserService,寫一個方法sayHello()
public interface UserService { void sayHello(); }
創(chuàng)建一個接口實現(xiàn)類,實現(xiàn)其方法,我們在方法中調(diào)用UserDaoImpl類的方法,代碼如下:
//<bean id="userService" class="com.sht.service.impl.UserServiceImpl"></bean> @Service(value = "userService") public class UserServiceImpl implements UserService { // <property name="userDao" ref="userDao"></property> @Autowired @Qualifier(value = "userDao") private UserDao userDao; //可以省略不寫 // public void setUserDao(UserDao userDao) { // this.userDao = userDao; // } @Override public void sayHello() { userDao.sayHello(); } }
分析: 注解@Service(value = "userService")就不多說了,使用方法跟第一組注解相同,我們在類中引入了private UserDao userDao;,該如何注入屬性呢?可以使用@Autowired+@Qualifier(value = “userDao”),其中的value屬性值相當于<property name="userDao" ref="userDao"></property>中的ref屬性值,可以開心的是,使用xml配置文件的方式,我們還要寫屬性對應的set方法,但是使用了注解后,就不需要寫set方法了,是不是很方便呢?@Autowired+@Qualifier(value = “userDao”)這兩個注解可以替換為@Resource(name=“userDao”),但是不建議使用;@Autowired+@Qualifier(value = “userDao”)還可以替換為單獨的@Autowired,表示的是根據(jù)類型注入屬性,當有多個相同類型時,就會報錯,謹慎使用哦
3、第三組注解
這一組注解的功能是字符串的注入,但是不單單是普通的字符串注入,讓我們寫一個代碼看看它的使用方法
- @Value:進行字符串的注入
- @PropertySource:引入外部properties文件
- @Bean:將方法的返回值注入spring容器中
在UserServiceImp類中加入一下代碼,使用@Value注解注入自己需要的字符串內(nèi)容
@Value("我是一棵卷心菜") private String name; public void print() { System.out.println(name); }
寫一個測試代碼,檢驗效果:
@Test public void test4() { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); UserServiceImpl userService = applicationContext.getBean(UserServiceImpl.class); userService.print(); }
運行結果:
這只是@Value注解的一種使用方法,接下來看看它的另一種使用方式
首先配置一個xml文件,用來配置Druid數(shù)據(jù)源,連接MySQL數(shù)據(jù)庫,這里的內(nèi)容在我的Spring專欄中講解的非常清楚,不懂的小伙伴們可以去學習一下
<?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" 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"> <context:property-placeholder location="classpath:jdbc.properties"/> <context:component-scan base-package="com.sht"/> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driver}"></property> <property name="url" value="${jdbc.url}"></property> <property name="username" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean> </beans>
在resources下配置一個jdbc.properties文件
jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/test jdbc.username=root jdbc.password=0315
接著在UserServiceImp類的上面加上注解@PropertySource(value = {"classpath:jdbc.properties"}),spring配置文件中<context:property-placeholder location=“classpath:jdbc.properties”/>就可以不要了,一個注解就解決了,是不是很方便呢?
需要注意的是,在@PropertySource注解中,通過進入源碼發(fā)現(xiàn),它的屬性值是一個數(shù)組類型,這就表明,我們可以引入多個properties文件
然后再UserServiceImp類中寫一個方法,用來獲取連接對象
@Value("${jdbc.driver}") private String driverClassName; @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String username; @Value("${jdbc.password}") private String password; @Bean("dataSource") public DataSource getDataSource() { DruidDataSource dataSource = new DruidDataSource(); dataSource.setDriverClassName(driverClassName); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); return dataSource; }
分析: 我們用注解@Value把properties文件的值拿到,然后在方法中進行連接配置,注解@Bean把獲取的對象放進spring容器中,方便以后的使用,它的屬性值是相當于bean標簽里面的id
配置是否成功呢?我們來寫一個測試代碼:
@Test public void test5() throws SQLException { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); DataSource dataSource = (DataSource) context.getBean("dataSource"); Connection connection = dataSource.getConnection(); System.out.println(connection); }
運行結果:
到這里,我們發(fā)現(xiàn)spring配置文件中還多了一個包掃描,孤苦伶仃的;我們該能不能不使用配置文件呢?答案是肯定可以的,接下來就來看看完全注解開發(fā)
四、完全注解開發(fā)
1、第一組注解
這三個注解不是很重要,了解即可
- @Scope:決定對象是多例還是單例
- @PostConstruct:標注初始化方法
- @PreDestroy:標注銷毀方法
2、第二組注解
這一組注解開始打開我們?nèi)⒔忾_發(fā)的大門
- @Configuration 用于指定當前類是一個 Spring 配置類,當創(chuàng)建容器時會從該類上加載注解
- @ComponentScan 用于指定 Spring 在初始化容器時要掃描的包。
- @PropertySource 用于加載.properties 文件中的配置
- @Import 用于導入其他配置類
使用全注解開發(fā),我們首先創(chuàng)建一個主類SpringConfig
@Configuration //<context:component-scan base-package="com.sht"/> @ComponentScan(value = {"com.sht"}) public class SpringConfig { private int age = 18; public void print() { System.out.println("我的年齡是" + age + "歲"); } }
分析: @Configuration告訴spring這是一個配置類,@ComponentScan的屬性值要填寫包掃描的路徑,它的功能跟<context:component-scan base-package="com.sht"/>一樣,到了這里,我們就可以完全的不需要spring配置文件了
接下來用代碼測試一下:
@Test public void test6() { ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); SpringConfig config = context.getBean(SpringConfig.class); config.print(); }
運行結果:
那么問題又來了,如果我有別的配置類,如何將它們放進spring容器里面呢?這時候就需要用到@Import注解了
上面內(nèi)容中,我在UserServiceImp類中寫一個方法,用來獲取連接對象,我現(xiàn)在把它們寫在一個UtilGetDataSource類中,代碼如下:
@PropertySource(value = {"classpath:jdbc.properties"}) public class UtilGetDataSource { @Value("${jdbc.driver}") private String driverClassName; @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String username; @Value("${jdbc.password}") private String password; @Bean("dataSource") public DataSource getDataSource() { DruidDataSource dataSource = new DruidDataSource(); dataSource.setDriverClassName(driverClassName); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); return dataSource; } }
我們要想使用這個方法,就需要把它放進spring容器中;用@Import注解,它的屬性值也是一個數(shù)組類型的,可以引入多個類
@Import(UtilGetDataSource.class) public class SpringConfig{ }
最后寫個測試類看看是否正確
@Test public void test6() throws SQLException { ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class); DataSource dataSource = (DataSource) context.getBean("dataSource"); Connection connection = dataSource.getConnection(); System.out.println(connection); }
運行結果:
五、總結
spring注解開發(fā)的使用大大簡化了xml的配置,注解有很多,我們應該在日常的學習中做好筆記,找時間復習,做到熟能生巧!
到此這篇關于Spring注解使用的文章就介紹到這了,更多相關Spring注解使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
基于SpringCloudGateway實現(xiàn)微服務網(wǎng)關的方式
Spring?Cloud?Gateway是Spring?官方基于Spring?5.0,Spring?Boot?2.0和Project?Reactor?等技術開發(fā)的網(wǎng)關,旨在為微服務架構提供一種簡單而有效的統(tǒng)一的API路由管理方式,對SpringCloudGateway實現(xiàn)微服務網(wǎng)關相關知識感興趣的朋友一起看看吧2021-12-12Spring Boot使用RestTemplate消費REST服務的幾個問題記錄
這篇文章主要介紹了Spring Boot使用RestTemplate消費REST服務的幾個問題記錄,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-06-06Java后端Tomcat實現(xiàn)WebSocket實例教程
WebSocket protocol 是HTML5一種新的協(xié)議。它實現(xiàn)了瀏覽器與服務器全雙工通信(full-duplex)。一開始的握手需要借助HTTP請求完成握手。本文給大家介紹Java后端Tomcat實現(xiàn)WebSocket實例教程,感興趣的朋友一起學習吧2016-05-05