Spring
01: Spring简介
02: Spring–Spring组成及拓展
03: Spring–IoC理论推导&IoC本质
04: Spring–第一个Spring程序HelloSpring&修改上节案例
05: Spring–IoC创建对象方式
06: Spring–Spring配置
07: Spring–依赖注入(Dependency Injection)
08: Spring–Bean的作用域
09: Spring–自动装配Bean(使用自动装配xml配置)
10: Spring–使用注解实现自动装配(推荐使用)
11: Spring–注解开发
12: Spring–使用JavaConfig实现配置
13: Spring–静态代理再理解&AOP
14: Spring–AOP(通过 Spring API 实现&自定义类来实现Aop&使用注解实现)
15: Spring–回忆Mybatis
16: Spring–整合Mybatis
17: Spring–Spring声明式事务
1. Spring–IoC创建对象方式
1.1 通过无参构造方法来创建(默认)
1.1.1 实体类
User.java
public class C{
private String name;
public User() {
System.out.println("user无参构造方法");
}
public void setName(String name) {
this.name = name;
}
public void show(){
System.out.println("name="+ name );
}
}
1.1.2 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="user" class="com.tian.pojo.User">
<property name="name" value="周小小同学"/>
</bean>
</beans>
1.1.3 测试类
Test.java
@org.junit.Test
public void test01() {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//在执行getBean的时候, user已经创建好了 , 通过无参构造
User user = (User) context.getBean("user");
//调用对象的方法 .
user.show();
}
运行结果:
结果可以发现,在调用show方法之前,User对象已经通过无参构造初始化了!
1.2 通过有参构造方法来创建
1.2.1 实体类UserT.java
package com.tian.pojo;
public class UserT {
private String name;
public UserT(String name) {
System.out.println("UserT有参构造方法");
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public void show() {
System.out.println("name=" + name);
}
}
1.2.2 beans.xml 有三种方式编写
1.2.2.1 根据index参数下标设置
<!-- 第一种根据index参数下标设置 -->
<bean id="userT" class="com.tian.pojo.UserT">
<!-- index指构造方法 , 下标从0开始 -->
<constructor-arg index="0" value="天天天"/>
</bean>
1.2.2.2 根据参数名字设置 (推荐使用)
<!-- 第二种根据参数名字设置 -->
<bean id="userT" class="com.tian.pojo.UserT">
<!-- name指参数名 -->
<constructor-arg name="name" value="天天天"/>
</bean>
1.2.2.3 根据参数类型设置
<!-- 第三种根据参数类型设置 -->
<bean id="userT" class="com.tian.pojo.UserT">
<constructor-arg type="java.lang.String" value="天天天"/>
</bean>
1.2.3 测试
@org.junit.Test
public void test02() {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserT user = (UserT) context.getBean("userT");
user.show();
}
运行结果:
1.3 结论
结论:在配置文件加载的时候。其中管理的对象都已经初始化了!单例模式!!!
Test.java
@org.junit.Test
public void test02() {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserT user01 = (UserT) context.getBean("userT");
UserT user02 = (UserT) context.getBean("userT");
System.out.println(user01 == user02);
}