Spring注释,读取属性

时间:2014-03-27 19:42:01

标签: java spring-annotations

我有一个小测试项目来测试Spring注释:

enter image description here

nejake.properties中的位置:

klucik = hodnoticka

并且在App.java中是:

@Configuration
@PropertySource("classpath:/com/ektyn/springProperties/nejake.properties")
public class App
{
    @Value("${klucik}")
    private String klc;



    public static void main(String[] args)
    {
        AnnotationConfigApplicationContext ctx1 = new AnnotationConfigApplicationContext();
        ctx1.register(App.class);
        ctx1.refresh();
        //
        App app = new App();
        app.printIt();
    }



    private void printIt()
    {
        System.out.println(klc);
    }
}

它应该在控制台上打印hodnoticka,但打印null - 字符串值未初始化。我的代码很糟糕 - 目前我没有使用注释驱动Spring的经验。上面的代码有什么不好?

2 个答案:

答案 0 :(得分:2)

您自己创建了对象

App app = new App();
app.printIt();

Spring应该如何管理实例并注入值?

但是你需要

@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
}

使属性可用。此外,由于在App的解析器之前初始化了为处理@Configuration而初始化的@Value bean,因此不会设置值字段。相反,声明一个不同的App bean并检索它

@Bean
public App appBean() {
    return new App();
}
...
App app = (App) ctx1.getBean("appBean");

答案 1 :(得分:0)

您需要从Spring bean访问该属性,并且需要正确连接属性。首先,添加到您的配置类:

@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() {

    PropertySourcesPlaceholderConfigurer props = new PropertySourcesPlaceholderConfigurer();
    props.setLocations(new Resource[] { new ClassPathResource("com/ektyn/springProperties/nejake.properties") }); //I think that's its absolute location, but you may need to play around with it to make sure
    return props;
}

然后你需要从Spring Bean中访问它们。通常,您的配置文件不应该是bean,因此我建议您创建一个单独的类,如下所示:

@Component //this makes it a spring bean
public class PropertiesAccessor {

   @Value("${klucik}")
    private String klc;

    public void printIt() {
        System.out.println(klc);
    }
}

最后,将其添加到您的配置中,以便找到PropertiesAccessor

@ComponentScan("com.ektyn.springProperties")

然后,您可以从应用上下文中访问PropertiesAccessor bean并调用其printIt方法。