首页 > 代码库 > (一)spring入门

(一)spring入门

一、applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
	<!-- 在容器文件中配置bean(service/dao/domain/action/数据源) -->
    <!-- bean元素作用:当spring框架加载时,spring就会自动创建一个bean对象,并放入内存中
	UserService userService=new UserService(); id号与userService对应
	userService.setName="张三" 
	 -->
    <bean id="userService" class="com.service.UserService">
        <property name="name">
      	  <value>张三</value>
        </property>
       <!--  在userService中引用byService bean 
       	第一个byeService,表示userService的属性,第二个表示引用
       -->
       <property name="byeService" ref="byeService"></property>
    </bean>
    <bean id="byeService" class="com.service.ByeService">
    	<property name="name" value="http://www.mamicode.com/小明"></property>
    </bean>
</beans>

二、Service

(一) UserService

public class UserService {
	
	private String name;
	ByeService byeService;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	public ByeService getByeService() {
		return byeService;
	}
	
	public void setByeService(ByeService byeService) {
		this.byeService = byeService;
	}

	public void sayHello(){
		System.out.println("hello~~~"+name);
		byeService.sayBye();
	}
}

(二)ByeService

public class ByeService {

	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	public void sayBye(){
		System.out.println("bye"+name);
	}
}

三、Test

public class Test {
	public static void main(String[] args) {
		//传统方法调用UserService的sayhello方法
//		UserService userService=new UserService();
//		userService.setName("张三");
//		userService.sayHello();
		//使用spring来完成
		//1、得到spring的applicationContext对象(容器对应)
		ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
		UserService us=(UserService) ac.getBean("userService");
		us.sayHello();
		
	        //使用Util得到applicationContext	
//((UserService)ApplicationContextUtil.getApplicationContext().getBean("userService")).sayHello(); //ac代表容器applicationContext //ByeService bs=(ByeService) ac.getBean("byeService"); //bs.sayBye(); } }

四、Util

final public  class ApplicationContextUtil {

	private static ApplicationContext ac=null;
	private ApplicationContextUtil(){
		
	}
	static{
		ac=new ClassPathXmlApplicationContext("applicationContext.xml");
	}
	public static ApplicationContext getApplicationContext(){
		return ac;
	}
}

  

  

  

  

(一)spring入门