简体   繁体   中英

How to autowire a member variable inside a class which is not maintained by spring container?

In my jsp, I have a custom tag

 <ex:SelfService />

which intrun calls the java class

public class SelfServiceClass extends SimpleTagSupport{

@Autowired
 private ReloadablePropertyManagerImpl reloadableProperty;


public ReloadablePropertyManagerImpl getReloadableProperty() {
    return reloadableProperty;
}

public void setReloadableProperty(
        ReloadablePropertyManagerImpl reloadableProperty) {
    this.reloadableProperty = reloadableProperty;
}

public void doTag() throws IOException {
    JspWriter out = getJspContext().getOut();
    out.println(getReloadableProperty().getPropertyValue("print.service"));
  }
}

And in my spring.xml I have configured the bean,

 <bean id="reloadableProperty" class="com.testing.portal.util.ReloadablePropertyManagerImpl" />

But I am getting null pointer exception when I call getPropertyValue() on reloadableProperty object. Any help will be much appreciated.

Since your class is not managed by Spring you have to load the ReloadablePropertyManagerImpl from the application context by yourself. In order to do so you should create a class which implements ApplicationContextAware with a static getter for the context.

See more in this sample .

Is Spring aware of SelfServiceClass class? It has to be. You either annotate it with @Component or it is returned by a @Configuration as a @Bean or include it as you did with reloadebleProperty in the xml, ie: make it a spring managed bean

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM