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

I used spring@value to get value from config, it works fine in other class(controller and other service), but it does not work in a model:

public final class Page {
  @Value("${defaultUrl}")
  private static String defaultUrl; 

  private String url;

  public Page(String url) {
    this.url = url;
  }
  public Page() {
    this(defaultUrl);
  }
}

In the above case, it is not possible to get defaultUrl from Spring.value. Anyone know why?

erkpwejropi
  • 391
  • 1
  • 7
  • 18

3 Answers3

7

Like duffymo says in his comment, using new means Spring isn't managing your new object. And so Spring won't inject anything into it. You would need to make your object a Spring-managed component to inject something.

Consider creating some kind of PageFactory component, putting a @Component annotation on it, and then using it to create your pages. That way you can inject what you need into the factory and use that to do whatever you like during page creation.

@Component
public class PageFactory {
    @Value("${defaultUrl}")
    private String defaultUrl;

    public Page create() {
        return new Page(defaultUrl);
    }
}

There is an advanced option, which I'll mention just for the sake of completeness. You can use @Configurable on your model classes to inject components into them. But there's some semi-tricky AOP configuration that I wouldn't recommend if you are just getting started with the framework.

0

Your class has to be a spring bean, see for reference the AutowiredAnnotationBeanPostProcessor (source)

Also do you a have context property place holder ?

<context:property-placeholder location="classpath:/default.properties"/>
Benoit Vanalderweireldt
  • 2,925
  • 2
  • 21
  • 31
-3

My best guess : The problem with this code is that it is trying to set a value on private member of class. try adding the setter method for this member.

something like

@Value("#{systemProperties.databaseName}")
public void setDatabaseName(String dbName) { ... }

@Value("#{strategyBean.databaseKeyGenerator}")
public void setKeyGenerator(KeyGenerator kg) { ... }

look here also How can I inject a property value into a Spring Bean which was configured using annotations?

Community
  • 1
  • 1