2014-11-03 213 views
0

在我当前的spring项目中,我正在寻找一种方法来为我的一些POJO类的属性赋值。根据变量赋值给变量

此功能类似于使用注释PathVariableModelAttribute用于在控制器的方法的一些参数的:当一个参数被注释与该注解的一个,所述自己的系统读出的值。此参数和分配给该变量,无需使用<variable> = <value>

在我的项目,我有一些POJO类是这样的:

class Class { 

    private <type> <attribute> 

    public <type> get<attribute>() { 
     return <attribute>; 
    } 

    public void set<attribute>(<type> <parameter>) { 
     <attribute> = <parameter>; 
    } 

} 

如果添加批注的属性(例如:@Setting),当我创建这个类的一个新实例,该系统应读取文件中的值并分配给变量。

任何人都可以告诉我该怎么做?

+1

这将有助于http://stackoverflow.com/questions/20782673/creating-custom-annotation-in-spring -mvc-and-getting-httpservletrequest-object – 2014-11-03 13:23:37

回答

1

您可以使用Spring @PropertySource & @Value注释。我的意思是这样的:

@Value("${sourceLocation:c:/temp/input}") 
    private String source; 

    @Value("${destinationLocation:c:/temp/output}") 
    private String destination; 

    @Autowired 
    private Environment environment; 

    public void readValues() { 
     System.out.println("Getting property via Spring Environment :" 
       + environment.getProperty("jdbc.driverClassName")); 

     System.out.println("Source Location : " + source); 
     System.out.println("Destination Location : " + destination); 

有一个很好的跟上时代的blogpost here

+0

是否可以使用'@ Value'参数作为我应用程序的其他类的现有方法的返回值而不是'$ {...}'? – 2014-11-03 14:50:00

+0

根据值的javadoc http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/factory/annotation/Value.html一个常见的用例是使用默认字段值“#{systemProperties.myProp}”样式表达式。所以我认为你需要一个注解'@PostConstruct'的初始化方法,并将其他类对象作为自动装配。您可以检查@PostConstructor注释。 – erhun 2014-11-03 15:50:06