spring-spring的配置

来源:互联网 发布:歌斐资产 知乎 编辑:程序博客网 时间:2024/06/04 20:04
applicationContext.xml:
<!-- 引入我们的db.properties --><context:property-placeholder location="classpath:com/dispatch/db.properties"/><?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:context="http://www.springframework.org/schema/context"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"><!-- 引入我们的db.properties --><context:property-placeholder location="classpath:com/dispatch/db.properties"/>
<!-- 字容器中配置bean --><!-- bean元素的作用是,当我们的spring框架加载的时候,spring就会自动的创建一个bean对象,并放入内存UserService userService=new UserService(); --><bean id="userService" class="com.service.UserService"><property name="name"><value>Han</value></property><!-- 在userService中引用 byeService --><property name="byeService" ref="byeService"></property></bean><bean id="byeService" class="com.service.ByeService"><property name="name" value="小明"/></bean></beans>
ByeService.java:
package com.service;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);}}
UserService.java
package com.service;public class UserService {private String name;private ByeService byeService;public ByeService getByeService() {return byeService;}public void setByeService(ByeService byeService) {this.byeService = byeService;}public String getName() {return name;}public void setName(String name) {this.name = name;}public void sayHello(){System.out.println("hello,"+name);byeService.sayBye();}}

test.java:

package com.test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.service.*;import com.util.ApplicationContextUtil;public class test {public static void main(String[] args) {// TODO Auto-generated method stub//1.得到spring的applicationContext对象(容器对象)//ApplicationContext ac=ApplicationContextUtil.getApplicationContext();//UserService us=(UserService) ac.getBean("userService");//us.sayHello();//ByeService bs=(ByeService) ac.getBean("byeService");//bs.sayBye();}}




原创粉丝点击