-1
@Component
@PropertySources({ @PropertySource("classpath:mail.properties") })
public class A implements B {

@Value("${mail.team.address}")
    private String teamAddress;

// has getter and setters .not shown for brevity.

Now when i call the class i get the value of teamAddress as NULL .But in the property file mail.team.address has some value.

My property file is present under src/main/resource folder

Making a call

 A a = new A ();
  a.someMethodinClassA();
Rahul
  • 163
  • 3
  • 12

3 Answers3

0

You can not create instance of class by yourself when you want Spring to resolve @Value annotation.

See documentation:

Note that actual processing of the @Value annotation is performed by a BeanPostProcessor which in turn means that you cannot use @Value within BeanPostProcessor or BeanFactoryPostProcessor types. Please consult the javadoc for the AutowiredAnnotationBeanPostProcessor class (which, by default, checks for the presence of this annotation).

Simple solution for you: just annotate class with any @Component annotation and let Spring to create an instance of your class.

Community
  • 1
  • 1
cici
  • 389
  • 3
  • 8
0

You can't create (with a "new" keywoard) for spring bean. If you do it like this, spring doesn't participate in the object creation and configuration, which means that there is no autowiring, the bean is not in Application Context, etc. And of course, @Value annotation won't be processed among other things

The better way is to inject the class A to the code that you used in your example:

A a = new A ();
a.someMethodinClassA();

Show become:

@Component 
public class SomeClass {
   private final A a;
   public SomeClass(A a) {
      this.a = a;
   }

   public void foo() {
         a.someMethodinClassA();
   }

}
Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97
0

You should read some basics around spring dependency injection. The class that you have autowired with @Component is scanned via component scanning and its object is created by spring container for you.

that is the reason you should not create the object yourself using new keyword.

wherever in your new class you want to use your class A object you can autowire it as below:

@Component
public class TestC{

private A a; // this object will be injected by spring for you

}
Sangam Belose
  • 4,262
  • 8
  • 26
  • 48