Spring的配置

创建名为springTest1的WEB工程,具体的文件结构图如下所示:

1,将Spring框架所需的JAR包加载到工程中(只需要基本的,这里加载的多了一些),具体如下:

2,在spring包中创建Friend接口,同时创建实现该接口的People类,

Friend接口:

View Code
package spring;

public interface Friend {
    public String sayHello(String s);

}

People类:

View Code
package spring;

public class People implements Friend {
    public String sayHello(String s){
        return "你好,"+s+",欢迎进入spring的学习!";
    }

}

3,在web.xml中创建web监听:

View Code
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <listener>
      <listener-class>
          org.springframework.web.context.ContextLoaderListener
      </listener-class>
  </listener>
</web-app>

4,创建配置文件Application.xml:

View Code
<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
    <bean id="People" class="spring.People">
    
    </bean>

</beans>

5,创建测试类TestSpringApplicationContext:

View Code
package spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class TestSpringApplicationContext {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ApplicationContext context=new FileSystemXmlApplicationContext("WebRoot/WEB-INF/classes/applicationContext.xml");
        Friend friend=(Friend)context.getBean("People");
        System.out.println(friend.sayHello("Friend"));

    }

}

6,运行测试类:

原文地址:https://www.cnblogs.com/lpshou/p/2794145.html