Spring Boot从应用程序属性文件中读取值

3

我不确定我是否理解正确,但从我的理解来看,我可以使用@Value注释从application.properties中读取值。

据我所知,这仅适用于Beans

我像这样定义了这样一个bean:

@Service
public class DBConfigBean {


    @Value("${spring.datasource.username}")
    private String userName;

    @Bean
    public String getName() {
        return this.userName;
    }
}

当应用程序启动时,我能够检索用户名,但是-在运行时如何访问此值?

每当我执行以下操作时

DBConfigBean conf = new DBConfigBean() conf.getName();

* 编辑 *

由于评论,我可以使用此配置DBConfigBean-但是我的初始问题仍然存在,即当我想在另一个类中使用它时。

@Configurable
public SomeOtherClass {

   @Autowired
   private DBConfigBean dbConfig; // IS NULL

   public void DoStuff() {
       // read the config value from dbConfig
   }
} 

如何在定义为bean的某个辅助类中读取DBConfig

谢谢

4个回答

3

2

你不应该使用new运算符来实例化你的服务。你应该注入它,例如:

@Autowired
private DBConfigBean dbConfig;

然后执行 dbConfig.getName();

而且在你的 getName() 方法中不需要任何 @Bean 装饰器

你只需要告诉 Spring 在哪里搜索你的注释 Bean 即可。因此,在你的配置文件中,你可以添加以下内容:

@ComponentScan(basePackages = {"a.package.containing.the.service",
                             "another.package.containing.the.service"})

编辑

@Value@Autowired等注解只能与Spring认知的bean一起使用。

将您的SomeOtherClass声明为bean,并在您的@Configuration类中添加包配置。

@Bean
private SomeOtherClass someOtherClass;

然后。
 @Configuration
 @ComponentScan(basePackages = {"a.package.containing.the.service"              
  "some.other.class.package"})
 public class AppConfiguration {

  //By the way you can also define beans like:
   @Bean 
   public AwesomeService service() {
       return new AwesomeService();
   }

 }

这个可以用,但我想在一个不是bean的类上使用它,因为它需要被实例化,比如ManagerClass。在这种情况下怎么做? - abdoe
依赖注入只能与bean一起使用。什么阻止您将ManagerClass声明为bean? - Eirini Graonidou
基本上就是我无法让它工作。当在AbstractDBManager上使用@Configurable时,我的@Autowired private DBConfigBean dbConfig;是空的。 - abdoe
只需添加@Bean注释,私有DbManager manager。然后不要忘记将DbManager的包添加到您的ComponentScan包中。 - Eirini Graonidou
抱歉,今天是我使用Spring Boot的第一天 - 如果没有示例,我无法理解它。 - abdoe
没问题,我更新了答案。但是正如@SimonMartinelli建议的那样,你应该查看文档。https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-spring-beans-and-dependency-injection.html - Eirini Graonidou

1

使用@Component注解包装您的DBConfig,并使用@Autowired注入它:

@Autowired
private DBConfig dbConfig;

0
只需将以下注解添加到您的DBConfigBean类中:
```java @PropertySource(value = {"classpath:application.properties"}) ```

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接