spring4.3.5基本配置

1.去官网下载必要的jar包,以及

2.新建一个web项目,在Window->Java->Build Path->User Libraries

按照步骤1,2把spring的jar放进去。

3.右键项目-》Build Path-》Configure Build Path-》

第1步选择User Library-》勾选Spring4.3,第2步选择commons-logging-1.2.jar。如此必要的jar包就导进来了。

接下来项目src下写一个类HelloSpring:

 1 package spring;
 2 
 3 public class HelloSpring {
 4     private String info;
 5     public void setInfo(String info) {
 6         this.info = info;
 7     }
 8     public void message()
 9     {
10         System.out.println("hello "+info);
11     }
12 }

然后在src下写一个xml配置文件,比如applicationContext.xml:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
 4     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
 5     <!-- 配置需要被Spring管理的Bean(创建,创建后放在了Spring IOC容器里面) -->
 6     <bean id="hello" class="spring.HelloSpring">
 7         <!-- 配置该Bean需要注入的属性(是通过属性set方法来注入的) -->
 8         <property name="info" value="zhangsan" />
 9     </bean>
10 </beans>  

接下来写一个测试类Test:

 1 package spring;
 2 
 3 import org.springframework.context.ApplicationContext;
 4 import org.springframework.context.support.ClassPathXmlApplicationContext;
 5 
 6 public class Test {
 7     public static void main(String[] args) {
 8         // TODO Auto-generated method stub
 9         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
10         HelloSpring hs = context.getBean("hello", HelloSpring.class);
11         hs.message();
12     }
13 }

测试类中的getBean第一个参数是和applicationContext.xml文件中的bean的id对应

 

posted @ 2017-06-09 17:28  我的名称很霸气  阅读(2027)  评论(0编辑  收藏  举报