传统方式
=====================UserService ===================
public interface UserService {
public void sayHello();
}
=====================UserServiceImpl===================
public class UserServiceImpl implements UserService{
// 添加属性:
private String name;
public void sayHello() {
System.out.println("Hello Spring" + name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
======================SpringDemo1 ====================
public class SpringDemo1 {
@Test
/**
* 传统方式开发
*/
public void demo1(){
// UserService userService = new UserServiceImpl();
//由于接口没有name属性,所以。只能用实现类,不能使用接口的形式
UserServiceImpl userService = new UserServiceImpl();
// 设置属性
userService.setName("张三");
userService.sayHello();
}
}
==============applicationContext.xml======================
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
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">
<!-- UserService的创建权交给了Spring -->
<bean id="userService" class="com.imooc.ioc.demo1.UserServiceImpl">
<property name="name" value="李四"/>
</bean>
</beans>
=====================springDemo1.java======================
/**
* Spring的方式实现
*/
@Test
public void demo2(){
//创建spring的工厂
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
//通过工厂获得
UserService userService=(UserService) applicationContext.getBean("userService");
userService.sayHello();
}