@Data
public class Hello {
private String str;
}
2.编写Sping配置文件
官网:
beans.xml:
3.测试
public class MyTest {
public static void main(String[] args) {
//获取Spring的上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//对象都在bean中管理,直接从bean中取出即可
Hello hello = (Hello) context.getBean("hello");
System.out.println(hello.toString());
}
}
总结:
-
Hello对象是由Spring创建的,Hello对象的属性是由SPringle容器设置的
-
控制反转:
-
控制:控制对象的创建,传统应用程序的对象是由程序本身控制创建的,使用Spring后,对象是由Spring创建的
-
反转:程序本身不创建对象,而变成被动的接收对象
-
-
依赖注入:利用Set方法注入
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
2.测试
public class MyTest {
public static void main(String[] args) {
//获取ApplicationContext;拿到Spring容器
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserServiceImpl userServiceImpl = (UserServiceImpl) context.getBean("UserServiceImpl");
userServiceImpl.getUser();
}
}
现在 , 不用再程序中去改动了 , 要实现不同的操作 , 只需要在xml配置文件中进行修改 .
所谓的IoC: 对象由Spring 来创建 , 管理 , 装配 !



