- 实体类
package com.faq.pojo;
public class Hello {
private String str;
public void setStr(String str) {
this.str = str;
}
public String getStr(){
return str;
}
@Override
public String toString(){
return "Hello{"+"str='"+str+'\''+'}';
}
}
- beans配置文件
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--使用Spring来创建对象,在spring中这些都成为bean
类型 变量名 = new 类型();
Hello hello = new Hello();
id = 变量名
class = new的对象
property 相当于给对象中的属性设值
bean = 对象 new Hello();
-->
<bean id="hello" class="com.faq.pojo.Hello">
<property name="str" value="Spring"/>
</bean>
</beans>
- 测试
import com.faq.pojo.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] agrs){
//用xml加载必须写这句,获取Spring的上下文对象,后面为配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//对象都在Spring中管理,使用时直接取出来就可以
Hello hello = (Hello)context.getBean("hello");
System.out.println(hello.toString());
}
}
输出:Hello{str='Spring'}
思考:
- Hello对象由谁创建的?
由Spring创建
- Hello对象的属性是由Spring容器设置的
控制反转:
控制:传统创建对象由程序本身控制,使用Spring后对象由Spring创建
反转:程序本身不创建对象,而变成被动的接受对象
所谓IOC就是对象由Spring来创建,管理,装配
修改spring-01-ioc1
beans.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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="mysqlImpl" class="com.faq.dao.UserDaoMysqlImpl"/>
<bean id="UserServiceImpl" class="com.faq.service.UserServiceImpl">
<!--
ref:引用Spring容器中创建好的对象
value:具体的值,基本数据类型
-->
<property name="userDao" ref="mysqlImpl"/>
</bean>
</beans>