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

Spring-简单bean的配置(使用bean.xml手动完成)

2016-09-22 18:47 453 查看
简单实例练习:

(1)接口
PersonService.java:
package com.sw.servc;

public interface PersonService {

void save();

}
(2)新建bean
PersonServiceBean.java:

package com.sw.service.impl;

import com.sw.servc.PersonService;

public class PersonServiceBean implements PersonService {
/* (non-Javadoc)
* @see com.sw.service.impl.PersonService#save()
*/
@Override
public void save(){
System.out.println("save()");
}
}

(3)新建beans.xml配置文件

bean.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-2.5.xsd"> <!-- id值第一个字母使用小写 -->
<bean id="personService" class="com.sw.service.impl.PersonServiceBean"></bean>

</beans>
(4)新建测试单元进行测试
package com.sw.junit.test;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.sw.servc.PersonService;

public class SpringTest {

@BeforeClass
public static void setUpBeforeClass() throws Exception {
}

@Test
public void instanceSpring () {
//实例化容器
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
//获取bean
PersonService personService=(PersonService) ctx.getBean("personService");//接口引用
//调用业务方法
personService.save();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐