您的位置:首页 > 编程语言 > Java开发

spring-1

2015-09-10 16:08 393 查看
1、新建一个spring-mvc工程,java工程即可。

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

package com.spring.service;

public class SpringService {
private String userName;

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public void sayHello() {
System.out.println("hello world " + userName);
}

}


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

package com.run;

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

import com.spring.service.SpringService;

public class Run {

public static void testRun(){
//1、创建spring的IOC容器对象
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//2、从IOC容器获取spring bean实例
//SpringService sService = (SpringService)ac.getBean("springService");
SpringService sService = (SpringService)ac.getBean(SpringService.class);
//3、调用sayHello方法
sService.sayHello();
}

public static void main(String[] args) {
testRun();
}
}


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

8、目录结构如图

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: