spring-1

1、新建一个spring-mvc工程,java工程即可。

2、目录结构,导入五个基本的jar包。

3、创建applicationContext.xml文件,引入xsd(用于约束xml文件可以出现的标签和标签出现的顺序),可以在下载的spring源码里面查看applicationContext.xml文件,看是如何引入xsd的。

另一种创建applicationContext.xml的方法,在src-->new -->other-->spring-->Spring Bean Configuration File

4、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"
 4     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 5 
 6 <bean class="com.spring.service.SpringService" id="springService">
 7     <property name="userName" value="lvyf">
 8          
 9     </property>
10 </bean>
11 </beans>
View Code

5、SpringService类

 1 package com.spring.service;
 2 
 3 public class SpringService {
 4     private String userName;
 5 
 6     public String getUserName() {
 7         return userName;
 8     }
 9 
10     public void setUserName(String userName) {
11         this.userName = userName;
12     }
13 
14     public void sayHello() {
15         System.out.println("hello world " + userName);
16     }
17 
18 }
View Code

6、从spring IOC获取SpringService实例,并调用方法

 1 package com.run;
 2 
 3 import org.springframework.context.ApplicationContext;
 4 import org.springframework.context.support.ClassPathXmlApplicationContext;
 5 
 6 import com.spring.service.SpringService;
 7 
 8 public class Run {
 9     
10     public static void testRun(){
11         //1、创建spring的IOC容器对象
12         ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
13         //2、从IOC容器获取spring bean实例
14         //SpringService sService = (SpringService)ac.getBean("springService");
15         SpringService sService = (SpringService)ac.getBean(SpringService.class);
16         //3、调用sayHello方法
17         sService.sayHello();
18     }
19     
20     public static void main(String[] args) {
21         testRun();
22     }
23 }

7、获取类实例的时候,有两种方法,一种是根据配置的ID,另一种是根据类类型,后一种可能会获取多个对象,所以最好用第一种。

8、目录结构如图

原文地址:https://www.cnblogs.com/fubaizhaizhuren/p/4798220.html