欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

springboot中@ConfigurationProperties無效果的解決方法

 更新時(shí)間:2024年06月14日 09:24:29   作者:五敷有你  
本文主要介紹了springboot中@ConfigurationProperties無效果,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

原因有一下幾點(diǎn)

前綴prefix沒寫對(duì)(概率不大,但也有)

@Data
@ConfigurationProperties(prefix = "message")
public class MyBean {


    private String msg;

    public MyBean(){
        System.out.println("MyBean初始化完成");
    }

  
}

2.類的方法中沒有setter

解決方法:

  • 用lombok的注解
  • 或者自己寫getter setter

3.寫了ConfigurationProperties但是沒寫Component

交給spring管理

4.是用AnnotationConfigApplicationContext(MyBeanConfig.class);獲取的bean不是一個(gè)spring容器(我的問題在于這個(gè))

用spring容器的自動(dòng)注入是有值的

但自己?jiǎn)伍_一個(gè)spring容器,這是兩個(gè),所以不會(huì)有值,有值的放到了第一個(gè)spring的容器中

第一個(gè)spring容器在

第二個(gè)spring容器是我在測(cè)試類開的,

@ConfigurationProperties 

在Spring Boot中注解@ConfigurationProperties有三種使用場(chǎng)景。

場(chǎng)景一

使用@ConfigurationProperties和@Component注解到bean定義類上,這里@Component代指同一類實(shí)例化Bean的注解。

基本使用實(shí)例如下:

// 將類定義為一個(gè)bean的注解,比如 @Component,@Service,@Controller,@Repository
// 或者 @Configuration
@Component
// 表示使用配置文件中前綴為user1的屬性的值初始化該bean定義產(chǎn)生的的bean實(shí)例的同名屬性
// 在使用時(shí)這個(gè)定義產(chǎn)生的bean時(shí),其屬性name會(huì)是Tom
@ConfigurationProperties(prefix = "user1")
public class User {
	private String name;
	// 省略getter/setter方法
}

對(duì)應(yīng)application.properties配置文件內(nèi)容如下:

user1.name=Tom

在此種場(chǎng)景下,當(dāng)Bean被實(shí)例化時(shí),@ConfigurationProperties會(huì)將對(duì)應(yīng)前綴的后面的屬性與Bean對(duì)象的屬性匹配。符合條件則進(jìn)行賦值。

場(chǎng)景二

使用@ConfigurationProperties和@Bean注解在配置類的Bean定義方法上。以數(shù)據(jù)源配置為例:

@Configuration
public class DataSourceConfig {

	@Primary
	@Bean(name = "primaryDataSource")
	@ConfigurationProperties(prefix="spring.datasource.primary")
	public DataSource primaryDataSource() {
		return DataSourceBuilder.create().build();
	}
}

這里便是將前綴為“spring.datasource.primary”的屬性,賦值給DataSource對(duì)應(yīng)的屬性值。

@Configuration注解的配置類中通過@Bean注解在某個(gè)方法上將方法返回的對(duì)象定義為一個(gè)Bean,并使用配置文件中相應(yīng)的屬性初始化該Bean的屬性。

場(chǎng)景三

使用@ConfigurationProperties注解到普通類,然后再通過@EnableConfigurationProperties定義為Bean。

@ConfigurationProperties(prefix = "user1")
public class User {
	private String name;
	// 省略getter/setter方法
}

這里User對(duì)象并沒有使用@Component相關(guān)注解。

而該User類對(duì)應(yīng)的使用形式如下:

@SpringBootApplication
@EnableConfigurationProperties({User.class})
public class Application {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }
}

上述代碼中,通過@EnableConfigurationProperties對(duì)User進(jìn)行實(shí)例化時(shí),便會(huì)使用到@ConfigurationProperties的功能,對(duì)屬性進(jìn)行匹配賦值。

到此這篇關(guān)于springboot中@ConfigurationProperties無效果的文章就介紹到這了,更多相關(guān)springboot @ConfigurationProperties內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論