如何在web.xml中加载springconfiguration xml?

时间:2017-02-19 14:40:26

标签: java xml spring-mvc

如何使用web.xml从我的applicaationContext加载bean并将bean注入My Controller ..我试图在web.xml中添加context-param并加载applicationContext.xml但是它确实无效..当我把mahasiswa在DispatcherServlet中,它可以工作..

我的控制器:

@Autowired private Mahasiswa mhs;

@RequestMapping("/")
public String Home(){
    mhs.tampilkan();
    return "index";
}

My Mahasiswa:

private String nama;

public String getNama() {
    return nama;
}

public void setNama(String nama) {
    this.nama = nama;
}

public void tampilkan(){
    System.out.println(this.nama);
}

web.xml:

<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
    <description></description>
    <display-name>DispatcherServlet</display-name>
    <servlet-name>DispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>DispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>

的DispatcherServlet-servlet.xml中

<bean id="jspViewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="WEB-INF/jsp/"></property>
    <property name="suffix" value=".jsp"></property>
</bean>

<context:annotation-config></context:annotation-config>
<mvc:annotation-driven></mvc:annotation-driven>
<context:component-scan base-package="com.belajar.spring.controller">
</context:component-scan>

的applicationContext.xml

<bean id="mahasiswa" class="com.belajar.spring.controller.Mahasiswa">
    <property name="nama" value="Dwi"></property>
</bean>

SS File

1 个答案:

答案 0 :(得分:0)

使用以下代码

替换web.xml中的现有代码以获取自定义应用程序上下文
<servlet>
    <servlet-name>DispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/DispatcherServlet-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>