Spring Bean管理注解方式代碼實例
更新時間:2020年03月20日 15:05:49 作者:shouyaya
這篇文章主要介紹了Spring Bean管理注解方式代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
1.使用注解的方式需要配置applicationContext.xml:
<?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 https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="org.yzytest1"></context:component-scan> <!--開啟包掃描-->
</beans>
2.將類交給Spring管理:
@Component("Demo1") //使用注解Component
public class Demo1 {
@Value("yzy")
private String name;
public void say(){
System.out.println("你好呀!"+name);
}
}

3.Spring的屬性注入:
普通的屬性注入,使用@Value屬性注入:
@Component("Demo1")
public class Demo1 {
@Value("yzy") //使用注解Value,屬性注入
private String name;
public void say(){
System.out.println("你好呀!"+name);
}
}
復(fù)雜的屬性注入,使用@Resource屬性注入:
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
@Component("Demo1")
public class Demo1 {
@Resource(name="User") //使用@Resource,屬性注入對象
private User user;
public void say(){
System.out.println("你好呀!"+user.getUsername());
}
}
4.Spring的其他注解:


以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot中快速實現(xiàn)郵箱發(fā)送代碼解析
這篇文章主要介紹了SpringBoot中快速實現(xiàn)郵箱發(fā)送代碼解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-08-08
SpringBoot中@Scheduled()注解以及cron表達式詳解
這篇文章主要介紹了SpringBoot中@Scheduled()注解以及cron表達式詳解,@Scheduled注解是Spring Boot提供的用于定時任務(wù)控制的注解,主要用于控制任務(wù)在某個指定時間執(zhí)行,或者每隔一段時間執(zhí)行,需要的朋友可以參考下2023-08-08
Java基礎(chǔ)知識之成員變量和局部變量淺顯易懂總結(jié)
從語法形式上,看成員變量是屬于類的,而局部變量是在方法中定義的變量或是方法的參數(shù);成員變量可以被public,private,static等修飾符所修飾,而局部變量不能被訪問控制修飾符及static所修飾2021-09-09
SpringBoot使用validation做參數(shù)校驗說明
這篇文章主要介紹了SpringBoot使用validation做參數(shù)校驗說明,首先通過添加hibernate-validator展開全文內(nèi)容,具有一定的參考價值,需要的小伙伴可以參考與喜愛2022-04-04
阿里規(guī)范:為何boolean類型變量命名禁用is開頭
這篇文章主要給大家介紹了關(guān)于阿里規(guī)范:為何boolean類型變量命名禁用is開頭的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08

