IOC相关内容
java包层级结构
- UserDao 接口
- UserDaoImpl 实现类
- UserService 业务接口
- UserServiceImpl 业务接口实现类
IOC本质
- 控制反转IOC(Inversion of Control),是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在spring中实现控制反转的是IOC容器,其实现方式是依赖注入(Dependency Injection, DI)
- 所谓的IOC,指的是,对象由Spring来创建,管理,装配
IOC创建对象的方式
- 使用无参的构造方法实现,默认
public class User {
private String name;
public User() {
System.out.println("User的无参构造!");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void show() {
System.out.println("name=" + name);
}
}
<?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 id="user" class="com.kuang.pojo.User">
<property name="name" value="程良飞"></property>
</bean>
</beans>
- 使用有参的构造方法实现
public class User {
private String name;
public User(String name) {
this.name=name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void show() {
System.out.println("name=" + name);
}
}
<?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 id="user" class="com.kuang.pojo.User">
<constructor-arg index="0" value="星时"></constructor-arg>
</bean>
<bean id="user" class="com.kuang.pojo.User">
<constructor-arg type="java.lang.String" value="浪迹"></constructor-arg>
</bean>
<bean id="user" class="com.kuang.pojo.User">
<constructor-arg name="name" value="阿飞"></constructor-arg>
</bean>
</beans>
- 其它
总结:在配置文件加载的时候,容器中管理的对象就已经初始化了
bean中value和ref的区别
<bean id="UserServiceImpl" class="com.kuang.service.UserServiceImpl">
<property name="userDao" ref="sqlServiceImpl"></property>
</bean>