国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

使用Java方法配置Spring代碼解析

瀏覽:5日期:2023-08-16 11:13:53

使用Java的方式配置Spring

我們現(xiàn)在要完全不使用Spring的xml配置,全權(quán)使用Java來(lái)配置Spring!

JavaConfig是Spring的一個(gè)子項(xiàng)目,在Spring4之后,他成為了一個(gè)核心功能。

使用Java方法配置Spring代碼解析

實(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)。

標(biāo)簽: Java
相關(guān)文章:
主站蜘蛛池模板: 巧家县| 莲花县| 鹿泉市| 楚雄市| 科尔| 江阴市| 庆安县| 罗田县| 宜黄县| 芒康县| 左贡县| 绵竹市| 石泉县| 永丰县| 额济纳旗| 聂荣县| 华安县| 平罗县| 梅州市| 定南县| 咸阳市| 太谷县| 永仁县| 阿克陶县| 乃东县| 荔波县| 辽源市| 高唐县| 齐河县| 高阳县| 义乌市| 博爱县| 泰宁县| 新宁县| 罗甸县| 高阳县| 鹤岗市| 舒兰市| 喜德县| 武冈市| 崇明县|