Spring 使用JavaConfig實現(xiàn)配置的方法步驟
更新時間:2020年01月07日 10:54:12 作者:像影子的人、
這篇文章主要介紹了Spring 使用JavaConfig實現(xiàn)配置的方法步驟,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
不使用Spring的XML配置,全權交給java來做!
JavaConfig是Spring的一個子項目,在Spring4之后,它稱為了Spring的核心功能!
實體類:
package com.lrx.poji; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; //說明這個類被Spring注冊到了容器中 @Component public class User { @Value("lixin") private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "User{" + "name='" + name + '\'' + '}'; } }
配置文件:
package com.lrx.config; import com.lrx.poji.User; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; //這個也會被Spring容器托管,因為它本來就是一個@Component // @Configuration代表一個類,就和我們之前的ApplicationContext.xml是一樣的 @Configuration @ComponentScan("com.lrx.poji") public class LiConfig { //注冊一個bean,就相當于xml寫的一個bean標簽 //這個方法的名字就相當于bean標簽中的ID屬性 //方法的返回值相當于bean標簽中的class屬性 @Bean public User getUser(){ return new User(); //就是要注入到bean的對象 } }
測試類:
import com.lrx.config.LiConfig; import com.lrx.poji.User; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class MyTest { public static void main(String[] args) { //如果完全使用了配置類方式去做,我們就只能通過AnnotationConfig上下文來獲取容器 // 然后通過配置類的class對象來加載! ApplicationContext context=new AnnotationConfigApplicationContext(LiConfig.class); User getUser= (User) context.getBean("user"); System.out.println(getUser.getName()); } }
這種純Java的配置方式在Spring Boot中隨處可見!
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
springboot中RestTemplate配置HttpClient連接池詳解
這篇文章主要介紹了springboot中RestTemplate配置HttpClient連接池詳解,這些Http連接工具,使用起來都比較復雜,如果項目中使用的是Spring框架,可以使用Spring自帶的RestTemplate來進行Http連接請求,需要的朋友可以參考下2023-11-11springboot項目連接多種數(shù)據(jù)庫該如何操作詳析
在Spring Boot應用中連接多個數(shù)據(jù)庫或數(shù)據(jù)源可以使用多種方式,下面這篇文章主要給大家介紹了關于springboot項目連接多種數(shù)據(jù)庫該如何操作的相關資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2024-08-08Spring Validation和Hibernate Validator結合國際化代碼實例
這篇文章主要介紹了Spring Validation和Hibernate Validator結合國際化代碼實例,我們需要對請求參數(shù)進行非空、長度、正確性進行校驗, 本文主要講解Spring Validation 和 Hibernate Validator, 同時整合i18n(國際化)實現(xiàn)參數(shù)校驗自動,需要的朋友可以參考下2023-10-10