使用Java方法配置Spring代碼解析
使用Java的方式配置Spring
我們現(xiàn)在要完全不使用Spring的xml配置,全權(quán)使用Java來(lái)配置Spring!
JavaConfig是Spring的一個(gè)子項(xiàng)目,在Spring4之后,他成為了一個(gè)核心功能。
實(shí)體類:
public class User { private String name; public String getName() { return name; } @Value('huba') //屬性注入值 public void setName(String name) { this.name = name; }}
配置類:
package com.kuang.config;import com.kuang.pojo.User;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Import;@Configuration //這個(gè)也會(huì)spring容器托管,注冊(cè)到容器中,因?yàn)樗緛?lái)就是一個(gè)@Component//@Configuration:代表這個(gè)一個(gè)配置類,就等同于beans.xml@ComponentScan('com.kuang.pojo')@Import(MyConfig2.class)public class MyConfig { //注冊(cè)一個(gè)bean,就相當(dāng)于我們之前寫的<bean>標(biāo)簽 //方法名就相當(dāng)于bean標(biāo)簽中的id //方法的返回值就相當(dāng)于bean標(biāo)簽中的class屬性 @Bean public User user(){ return new User();//就是返回要注入bean的對(duì)象 }}
測(cè)試類:
import com.kuang.config.MyConfig;import com.kuang.pojo.User;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class myTest { @Test public void test(){ //如果完全使用配置類方式,只能通過AnnotationConfigApplicationContext獲取容器,通過配置類的class對(duì)象加載! ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class); User user = context.getBean('user', User.class); System.out.println(user.getName()); }}
這種純Java的配置方式,在SpringBoot中隨處可見!
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 怎樣才能用js生成xmldom對(duì)象,并且在firefox中也實(shí)現(xiàn)xml數(shù)據(jù)島?2. 存儲(chǔ)于xml中需要的HTML轉(zhuǎn)義代碼3. javascript xml xsl取值及數(shù)據(jù)修改第1/2頁(yè)4. asp知識(shí)整理筆記4(問答模式)5. 小技巧處理div內(nèi)容溢出6. ASP中格式化時(shí)間短日期補(bǔ)0變兩位長(zhǎng)日期的方法7. ASP實(shí)現(xiàn)加法驗(yàn)證碼8. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)9. js的一些潛在規(guī)則使用分析10. phpstudy apache開啟ssi使用詳解
