帶你快速入門掌握Spring的那些注解使用
一、前言
這是spring專欄的第三篇文章,是關(guān)于spring的注解開發(fā),包括完全注解和非完全注解開發(fā)。自己整理了學(xué)習(xí)的筆記,希望大家喜歡。
二、基本介紹
前面兩篇關(guān)于spring的知識(shí)點(diǎn)學(xué)習(xí),我都是用xml配置文件來一步步講解的,但是Spring是輕代碼而重配置的框架,xml配置文件比較繁重,影響開發(fā)效率,所以注解開發(fā)是一種趨勢,注解代替xml配置文件可以簡化配置,提高開發(fā)效率。
因此,我在寫這篇文章之前,一直在思考,如何用一種方式來讓小伙伴們理解的更加深刻呢?最后決定,我在講解注解使用的時(shí)候,要與使用xml配置文件的方式進(jìn)行一個(gè)對(duì)比,盡量讓小伙伴們知其所以然!
三、非全注解開發(fā)
1、第一組注解
這組注解關(guān)于對(duì)象的實(shí)例化創(chuàng)建,在功能上都沒有區(qū)別
- @Component 使用在類上用于實(shí)例化Bean
- @Controller 使用在web層類上用于實(shí)例化Bean
- @Service 使用在service層類上用于實(shí)例化Bean
- @Repository 使用在dao層類上用于實(shí)例化Bean
接下來讓我們從具體的代碼分析,理解和掌握它們吧!
先創(chuàng)建一個(gè)UserDao接口,隨便寫一個(gè)sayHello()方法
public interface UserDao {
void sayHello();
}
然后寫一個(gè)接口實(shí)現(xiàn)類UserDaoImpl類,實(shí)現(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")就表示把這個(gè)類的實(shí)例放進(jìn)了spring容器中,value = "userDao"就相當(dāng)于<bean id="userDao" class="com.sht.dao.impl.UserDaoImpl"></bean>中的id屬性值,我們使用注解的時(shí)候,就不需要在指定類的包路徑了,因此省略了class屬性值
注意,使用非全注解開發(fā),意味著要配置spring文件,與之前不同的是,我們要在配置文件中加上一個(gè)包掃描,才能讓注解生效
<?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>
寫一個(gè)測試代碼:
@Test
public void test4() {
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = applicationContext.getBean(UserService.class);
userService.sayHello();
}
運(yùn)行結(jié)果:

2、第二組注解
這一組注解的功能是屬性注入,讓我們寫一個(gè)代碼看看他們的使用方法
- @Autowired
- @Resource
- @Qulifier:和@Autowired一起使用
創(chuàng)建一個(gè)接口UserService,寫一個(gè)方法sayHello()
public interface UserService {
void sayHello();
}
創(chuàng)建一個(gè)接口實(shí)現(xiàn)類,實(shí)現(xiàn)其方法,我們?cè)诜椒ㄖ姓{(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")就不多說了,使用方法跟第一組注解相同,我們?cè)陬愔幸肓藀rivate UserDao userDao;,該如何注入屬性呢?可以使用@Autowired+@Qualifier(value = “userDao”),其中的value屬性值相當(dāng)于<property name="userDao" ref="userDao"></property>中的ref屬性值,可以開心的是,使用xml配置文件的方式,我們還要寫屬性對(duì)應(yīng)的set方法,但是使用了注解后,就不需要寫set方法了,是不是很方便呢?@Autowired+@Qualifier(value = “userDao”)這兩個(gè)注解可以替換為@Resource(name=“userDao”),但是不建議使用;@Autowired+@Qualifier(value = “userDao”)還可以替換為單獨(dú)的@Autowired,表示的是根據(jù)類型注入屬性,當(dāng)有多個(gè)相同類型時(shí),就會(huì)報(bào)錯(cuò),謹(jǐn)慎使用哦
3、第三組注解
這一組注解的功能是字符串的注入,但是不單單是普通的字符串注入,讓我們寫一個(gè)代碼看看它的使用方法
- @Value:進(jìn)行字符串的注入
- @PropertySource:引入外部properties文件
- @Bean:將方法的返回值注入spring容器中
在UserServiceImp類中加入一下代碼,使用@Value注解注入自己需要的字符串內(nèi)容
@Value("我是一棵卷心菜")
private String name;
public void print() {
System.out.println(name);
}
寫一個(gè)測試代碼,檢驗(yàn)效果:
@Test
public void test4() {
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("applicationContext.xml");
UserServiceImpl userService = applicationContext.getBean(UserServiceImpl.class);
userService.print();
}
運(yùn)行結(jié)果:

這只是@Value注解的一種使用方法,接下來看看它的另一種使用方式
首先配置一個(gè)xml文件,用來配置Druid數(shù)據(jù)源,連接MySQL數(shù)據(jù)庫,這里的內(nèi)容在我的Spring專欄中講解的非常清楚,不懂的小伙伴們可以去學(xué)習(xí)一下
<?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下配置一個(gè)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”/>就可以不要了,一個(gè)注解就解決了,是不是很方便呢?

需要注意的是,在@PropertySource注解中,通過進(jìn)入源碼發(fā)現(xiàn),它的屬性值是一個(gè)數(shù)組類型,這就表明,我們可以引入多個(gè)properties文件

然后再UserServiceImp類中寫一個(gè)方法,用來獲取連接對(duì)象
@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文件的值拿到,然后在方法中進(jìn)行連接配置,注解@Bean把獲取的對(duì)象放進(jìn)spring容器中,方便以后的使用,它的屬性值是相當(dāng)于bean標(biāo)簽里面的id
配置是否成功呢?我們來寫一個(gè)測試代碼:
@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);
}
運(yùn)行結(jié)果:

到這里,我們發(fā)現(xiàn)spring配置文件中還多了一個(gè)包掃描,孤苦伶仃的;我們?cè)撃懿荒懿皇褂门渲梦募??答案是肯定可以的,接下來就來看看完全注解開發(fā)
四、完全注解開發(fā)
1、第一組注解
這三個(gè)注解不是很重要,了解即可
- @Scope:決定對(duì)象是多例還是單例
- @PostConstruct:標(biāo)注初始化方法
- @PreDestroy:標(biāo)注銷毀方法


2、第二組注解
這一組注解開始打開我們?nèi)⒔忾_發(fā)的大門
- @Configuration 用于指定當(dāng)前類是一個(gè) Spring 配置類,當(dāng)創(chuàng)建容器時(shí)會(huì)從該類上加載注解
- @ComponentScan 用于指定 Spring 在初始化容器時(shí)要掃描的包。
- @PropertySource 用于加載.properties 文件中的配置
- @Import 用于導(dǎo)入其他配置類
使用全注解開發(fā),我們首先創(chuàng)建一個(gè)主類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這是一個(gè)配置類,@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();
}
運(yùn)行結(jié)果:

那么問題又來了,如果我有別的配置類,如何將它們放進(jìn)spring容器里面呢?這時(shí)候就需要用到@Import注解了
上面內(nèi)容中,我在UserServiceImp類中寫一個(gè)方法,用來獲取連接對(duì)象,我現(xiàn)在把它們寫在一個(gè)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;
}
}
我們要想使用這個(gè)方法,就需要把它放進(jìn)spring容器中;用@Import注解,它的屬性值也是一個(gè)數(shù)組類型的,可以引入多個(gè)類
@Import(UtilGetDataSource.class)
public class SpringConfig{
}
最后寫個(gè)測試類看看是否正確
@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);
}
運(yùn)行結(jié)果:

五、總結(jié)
spring注解開發(fā)的使用大大簡化了xml的配置,注解有很多,我們應(yīng)該在日常的學(xué)習(xí)中做好筆記,找時(shí)間復(fù)習(xí),做到熟能生巧!
到此這篇關(guān)于Spring注解使用的文章就介紹到這了,更多相關(guān)Spring注解使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java求數(shù)組元素重復(fù)次數(shù)和java字符串比較大小示例
這篇文章主要介紹了java求數(shù)組元素重復(fù)次數(shù)和java字符串比較大小示例,需要的朋友可以參考下2014-04-04
java數(shù)據(jù)結(jié)構(gòu)ArrayList詳解
本文詳細(xì)講解了java數(shù)據(jù)結(jié)構(gòu)ArrayList的用法,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-12-12
一文看懂springboot實(shí)現(xiàn)短信服務(wù)功能
項(xiàng)目中的短信服務(wù)基本上上都會(huì)用到,簡單的注冊(cè)驗(yàn)證碼,消息通知等等都會(huì)用到。這篇文章主要介紹了springboot 實(shí)現(xiàn)短信服務(wù)功能,需要的朋友可以參考下2019-10-10

