0

In my current spring project, I am looking for a way to assign some value for the attributes of some of the my POJO classes.

This feature is similar to the use of the annotations PathVariable and ModelAttribute for some parameters in the methods of a controller: when a parameter is annotated with one of this annotations, the own system read the value for this parameter and assign to the variable, without need use <variable> = <value>.

In my project, I have some POJO class like this:

class Class {

    private <type> <attribute>

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

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

}

if add an annotation to the attribute (for instance: @Setting), when I create a new instance of this class, the system should read a value in a file and assign to the variable.

Anyone can tell me how to do this?

Kleber Mota
  • 8,521
  • 31
  • 94
  • 188
  • 1
    This could help http://stackoverflow.com/questions/20782673/creating-custom-annotation-in-spring-mvc-and-getting-httpservletrequest-object – Naveen Ramawat Nov 03 '14 at 13:23

1 Answers1

1

You can use Spring @PropertySource & @Value annotations. I mean something like this:

 @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);

There is a good up-to-date blogpost here

erhun
  • 3,549
  • 2
  • 35
  • 44
  • Is it possible use for parameter of `@Value` the return value of a existing method from other class of my application, instead of `${...}`? – Kleber Mota Nov 03 '14 at 14:50
  • http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/factory/annotation/Value.html according to javadoc of value A common use case is to assign default field values using "#{systemProperties.myProp}" style expressions. So i think you need an initialize method which is annotated '@PostConstruct', and get the other class object as autowired. You can check @PostConstructor annotation. – erhun Nov 03 '14 at 15:50