简体   繁体   中英

Spring MVC: How to get context param when instantiate the bean?

this is simple question,

how to get servlet context parameter when spring instantiate the bean?

my servlet context xml

<beans:bean id="ApplicationInfo" class="xx.xx.xx.ApplicationInfo"/>

In my code

public class ApplicationInfo{
   ApplicationInfo()
   {
      //get context.xml or web.xml parameter
      String xxx = .......;
   }
}

my pom.xml

<org.springframework-version>3.2.11.RELEASE</org.springframework-version>
<org.aspectj-version>1.6.9</org.aspectj-version>
<org.slf4j-version>1.5.10</org.slf4j-version>
<org.springsecurity-version>3.2.5.RELEASE</org.springsecurity-version>
<org.springjpa-version>1.1.0.RELEASE</org.springjpa-version>
<hibernate.version>4.1.6.Final</hibernate.version>
<postgresql.version>9.1-901-1.jdbc4</postgresql.version>
<tiles-version>2.2.2</tiles-version>
<jackson-json-version>2.1.0</jackson-json-version>

Note: i tried to get servlet context by using @annotation ,however it is nullpointer.

在此处输入图片说明

If you want to access autowired bean in constructor, you have to use constructor type injection:

@Component
public class ApplicationInfo {
    private final FooService fooService;

    @Autowired
    public ApplicationInfo(ServletContext servletContext, FooService fooService) {
        this.fooService = fooService;

        // do something here
    }
}

If you have to (or want to) stick to XML beans definition you've got to make your class implement ServletContextAware interface, which makes Spring automatically set this dependency through setter. Instead of accessing it in constructor, you do it in method annotated with @PostConstruct which is fired when bean is fully initialized:

public class ApplicationInfo implements ServletContextAware {
    private final FooService fooService;
    private ServletContext servletContext;

    public ApplicationInfo(FooService fooService) {
        this.fooService = fooService;
    }

    @PostConstruct
    public void init() {
        // now you fooService and servletContext are set
    }

    @Override
    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }
}
<bean class="demo.ApplicationInfo">
    <constructor-arg name="fooService" ref="fooService" />
</bean>

<bean id="fooService" class="demo.FooService"/>

Try with @Value annotation

public class ApplicationInfo {
   @Value("${parameterName}")
   private String parameter;
}

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