gorootde
gorootde

Reputation: 4073

Spring's value annotation does not work in constructor argument

Service

@Service
class Foo{
   Foo(@Value("${my.property}")int delay){
    ...
   }
}

Consumer

class Bar {
    @Autowire
    Foo foo;
}

beans.xml

<context:component-scan base-package="foo.*" />
<context:spring-configured />
<context:property-placeholder location="classpath:foo/internal.properties"/>

internal.properties does contain my.property=5000. But it seems like spring does not even care about the @Value annotation. If I run the application, spring complains about that there is no default constructor found.

Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [foo.Foo]: No default constructor found; nested exception is java.lang.NoSuchMethodException...

I even tried to configure the parameter in beans.xml using the constructor-arg tag. This method produces the same error.

Why is the value injection not working?

Upvotes: 1

Views: 4183

Answers (2)

A0__oN
A0__oN

Reputation: 9110

@Service
class Foo{
  @Autowired
  Foo(@Value("${my.property}")int delay){
    ...
   }
}

You forget to add @Autowired in your constructor.

From Spring 4.3 we no longer need to specify the @Autowired annotation if the target bean only define one constructor

Upvotes: 5

Hrabosch
Hrabosch

Reputation: 1583

I think your problem is that, you are missing constructor (check your exception). For Bean is important to create default (no args) constructor. More about this you can read here. This is good article.

Upvotes: -2

Related Questions