最近有人私信我说,我写的博客有些肤浅,没有深究,在此我统一回复一下,这些博客大多都是概念性东西,是用通俗的例子让你理解这个技术或者知识到底是怎么一样原理。
所以我在后面都加着适合新人,我们都是从新人走过来的,知道初学者的那种迷茫,只会代码,不懂原理和含义,就比如,注解,你不去学习理解,初学者根本就不知道那是个什么东西,为什么要使用注解。
如果是资深大牛,那就不要看了,还是那句话,适合新人。
——————————————————————————————————
1,什么是SpringIOC?
SpringIOC是Spring的核心之一,是控制反转;
简单说就是创建对象由以前的程序员自己new 构造方法来调用,变成了交由Spring创建对象
2,SpringIOC容器作用
- 创建对象
- 处理对象的依赖关系
3, SpringIOC创建对象的几种方式;
在这里我直接写测试代码了,之前写了一片关于Spring的文章,不懂得可以去看看,这里的代码和之前的都是相通的;
Spring学习(适合新人)
-
构造函数方式;
1.1 无参构造方式
在Spring.xml创建一个bean
<bean id="userEntity" class="entity.UserEntity" ></bean>
测试代码
public class SpringTest02 {
public static void main(String[] args) {
//1.先加载Spring容器
ClassPathXmlApplicationContext Context = new ClassPathXmlApplicationContext("Spring002.xml");
//根据bean的id,查找对象
UserEntity bean1 = (UserEntity) Context.getBean("userEntity");
System.out.println(bean1);
}
}
结果
1.2 有参构造方式
在Spring.xml创建一个bean
<!-- 有参构造函数 -->
<bean id="userEntity1" class="entity.UserEntity">
<constructor-arg name="name" value="莫参商"></constructor-arg>
<constructor-arg name="age" value="18"></constructor-arg>
</bean>
测试代码:
public class SpringTest02 {
public static void main(String[] args) {
//1.先加载Spring容器
ClassPathXmlApplicationContext Context = new ClassPathXmlApplicationContext("Spring002.xml");
//根据bean的id,查找对象
UserEntity bean1 = (UserEntity) Context.getBean("userEntity1");
System.out.println(bean1.toString());
}
}
结果
2. 实例工厂类创建
先创建一个实例化工厂类
package entity;
public class ObjectFactory {
/**
* (实例工厂)
* @return
*/
public UserEntity getUserEntity(){
return new UserEntity("莫参商",18);
}
}
设置bean
<!-- 实例化工厂方法 -->
<bean id="ObjectFactory" class="entity.ObjectFactory"></bean>
<bean id="getUserEntity" factory-bean="ObjectFactory" factory-method="getUserEntity"></bean>
调用:
public class SpringTest02 {
public static void main(String[] args) {
//1.先加载Spring容器
ClassPathXmlApplicationContext Context = new ClassPathXmlApplicationContext("Spring002.xml");
//根据bean的id,查找对象
UserEntity bean1 = (UserEntity) Context.getBean("getUserEntity");
System.out.println(bean1.toString());
}
}
结果
2.2静态工厂类方法创建
在实例化工场创建静态方法
package entity;
public class ObjectFactory {
/**
* (实例工厂)
* @return
*/
public UserEntity getUserEntity(){
return new UserEntity("莫参商",18);
}
public static UserEntity getStaticUserEntity(){
return new UserEntity("莫参商",28);
}
}
设置bean
//静态工厂类方法
<bean id="getStaticUserEntity" class="entity.ObjectFactory" factory-method="getStaticUserEntity"></bean>
调用:
public class SpringTest02 {
public static void main(String[] args) {
//1.先加载Spring容器
ClassPathXmlApplicationContext Context = new ClassPathXmlApplicationContext("Spring002.xml");
//根据bean的id,查找对象
UserEntity bean1 = (UserEntity) Context.getBean("getStaticUserEntity");
System.out.println(bean1.toString());
}
}
结果: