2014-03-27 123 views
0

我小的测试项目,测试Spring注解: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

您创建的对象自己

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

春季应该如何管理实例,并注入价值?

您将需要但是

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

使可用属性。另外,因为初始化处理@ConfigurationApp bean已在解析器@Value之前初始化,所以值字段将不会被设置。相反,声明不同的App豆和检索

@Bean 
public App appBean() { 
    return new App(); 
} 
... 
App app = (App) ctx1.getBean("appBean"); 
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方法。