Spring Bean管理注解方式代碼實(shí)例
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> <!--開(kāi)啟包掃描--></beans>
2.將類交給Spring管理:
@Component('Demo1') //使用注解Componentpublic 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,屬性注入對(duì)象 private User user; public void say(){ System.out.println('你好呀!'+user.getUsername()); }}
4.Spring的其他注解:
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. xml中的空格之完全解說(shuō)2. asp讀取xml文件和記數(shù)3. IE6/IE7/IE8/IE9中tbody的innerHTML不能賦值的完美解決方案4. 利用CSS制作3D動(dòng)畫5. jsp+servlet簡(jiǎn)單實(shí)現(xiàn)上傳文件功能(保存目錄改進(jìn))6. 匹配模式 - XSL教程 - 47. WML語(yǔ)言的基本情況8. 小技巧處理div內(nèi)容溢出9. jsp cookie+session實(shí)現(xiàn)簡(jiǎn)易自動(dòng)登錄10. xpath簡(jiǎn)介_(kāi)動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
