当前位置: 首页 > 工具软件 > Bean Machine > 使用案例 >

spring boot 配置类中构造Bean指定bean属性

师博
2023-12-01

spring 的xml配置中使用标签可以给bean的属性赋值,在spring boot 中,使用@Bean标签时,如果需要给所构造的bean的属性赋值,可以使用如下方法。

1.自定义(也可以用默认)的配置文件,给所需属性赋值

vesta.machineId = 3
vesta.providerType = PROPERTY

2.配置类中使用@PropertySource("classpath:vesta-service.properties")指定配置文件位置,@ConfigurationProperties(prefix="vesta")为所构造bean属性赋值

package com.example.demo.configuration;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import com.robert.vesta.service.factory.IdServiceFactoryBean;
import com.robert.vesta.service.intf.IdService;

@Configuration
@PropertySource("classpath:vesta-service.properties")
public class VestaConfiguration {

@Bean(initMethod = "init")  
@ConfigurationProperties(prefix="vesta")  
public IdServiceFactoryBean getIdServiceFactoryBean() throws Exception{

    return new IdServiceFactoryBean();  
}  

}

转载于:https://my.oschina.net/u/3657235/blog/2218833

 类似资料: