1.写Service接口:
public interface UserSerivce {
public void add();
}
2.写Sercice实现类
public class UserServiceimpl implements UserSerivce {
private String name;//利用xml注入Value
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void add(){
System.out.println("创建用户..."+name);
}
}
3.配置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 name="demo" class="com.demo.service.impl.UserServiceimpl">
<property name="name" value="zhangsan"></property>
</bean>
</beans>
4.写单元测试
public class test {
//以前创建的方式
@Test
public void testOld(){
UserSerivce userSerivce =new UserServiceimpl();
userSerivce.add();
}
//Spring方式
@Test
public void testNow(){
ApplicationContext context =new ClassPathXmlApplicationContext("UserMapper.xml");
UserServiceimpl userServiceimpl = (UserServiceimpl) context.getBean("demo");
userServiceimpl.add();
}
}
总结:开发者不需要自己New对象,Spring自己完成。