1
import org.springframework.beans.factory.annotation.Value;

public class PropertyReader {
    @Value("${spring.active.profiles")
    private String profile;

    @Nonnull
    public String getProfile() {
        return profile;
    }
}

and this is test I have

public class PropertyReaderTest {

    @Test
    public void testGetProfile() throws Exception {
        System.out.printf(System.getProperty("spring.active.profiles"));
        assertEquals("development", new PropertyReader().getProfile());
    }
}

and the dependency I have is

<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.0.3.RELEASE</version>
        </dependency>
    </dependencies>

and I see

development
java.lang.AssertionError: 
Expected :development
Actual   :null
daydreamer
  • 87,243
  • 191
  • 450
  • 722
  • 2
    You are constructing a new instance of the class yourself. Spring isn't in play anywhere so will not do injection/replacement of any kind. – M. Deinum May 01 '14 at 18:42
  • possible duplicate of [Why is my Spring @Autowired field null?](http://stackoverflow.com/questions/19896870/why-is-my-spring-autowired-field-null) – chrylis -cautiouslyoptimistic- May 01 '14 at 18:43
  • This is in no way a duplicate of Why is my Spring @Autowired field null. The cause of this null is differennt. – DwB May 01 '14 at 18:59
  • It isn't, the same issue applies in both cases a new instance (outside of Spring) is created. – M. Deinum May 01 '14 at 19:38

2 Answers2

1

first thing i am assuming your syntax is correct and its type mistake for @value that you have posted.

 @Value("${spring.active.profiles}")

Now to use @value, you must make the class register as a spring bean and that too using only annotation. even if you register class using xml also your @value will not work.

and also get the bean using spring container to happen automatic injection, dont create object by yourselves using new.

Solution to your above problem

1)

@Component
PropertyReader 

make class PropertyReader as a spring bean using @Component.

2)load bean from application context in your test class, dont use new to create it.

Karibasappa G C
  • 2,686
  • 1
  • 18
  • 27
0

Yuo should put @Service on the class PropertyReader or you should use a XML spring file in order to define the bean and let to spring to valorize properties

Angelo Immediata
  • 6,635
  • 4
  • 33
  • 65