Spring Bean管理注解方式代碼實例
更新時間:2020年03月20日 15:05:49 作者:shouyaya
這篇文章主要介紹了Spring Bean管理注解方式代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
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); } }
復雜的屬性注入,使用@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)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Spring實戰(zhàn)之ResourceLoaderAware加載資源用法示例
這篇文章主要介紹了Spring實戰(zhàn)之ResourceLoaderAware加載資源用法,結合實例形式分析了spring使用ResourceLoaderAware加載資源相關配置與操作技巧,需要的朋友可以參考下2020-01-01深入解析System.load 與 System.loadLibrary
以下是對System.load與System.loadLibrary進行了詳細的分析介紹。需要的朋友可以過來參考下2013-08-08