文章目录

  • 一、Spring配置
  • 1.1、起别名
  • 1.2、Bean的配置
  • 1.3、import
  • 二、依赖注入
  • 2.1、构造器注入
  • 2.2、Set注入(重点)
  • 2.3、拓展方式注入
  • 2.4、Bean的作用域
  • 三、Bean的自动装配
  • 3.1、测试环境搭建
  • 3.2、ByName自动装配
  • 3.3、ByType自动装配
  • 3.4、使用注解实现自动装配
  • 3.4.1、 @Autowired
  • 3.4.2、@Qualifier
  • 3.4.3、@Resource
  • 3.5、小结


一、Spring配置

1.1、起别名

alias 设置别名 , 为bean设置别名 , 可以设置多个别名

<!-- 别名,如果添加了别名,就可以使用别名获取到对象  -->
<alias name="User" alias="user"></alias>

1.2、Bean的配置

<!--
	id :bean的唯一标识符,也就是相当于学的对象名
	class:bean对象所对应的全限定名:包名 + 类名
	name:也是别名,而且name可以同时起多个别名
-->
<bean id="userT" class="com.study.pojo.UserT" name="user2,u2">
	<property name="name" value="name"></property>
</bean>

1.3、import

一般用于团队开发使用,可以将多个配置文件导入合并为一个

假设现在项目中有多个人开发,分别负责不同的类开发,不同的类需要注册在不同的bean中,我们可以利用import将所有人的beans.xml合并为一个总的。使用的时候直接使用总的配置就可以

<import resource="beans.xml"></import>

二、依赖注入

依赖注入:set注入

  • 依赖:bean对象的创建依赖于容器
  • 注入:bean对象中的所有属性,由容器来注入

2.1、构造器注入

在IOC创建对象方式讲过

2.2、Set注入(重点)

要求被注入的属性,必须有set方法,set方法的方法名由set + 属性首字母大写
如果属性是boolean类型,没有set方法,是 is

  1. 环境搭建
    Address.java
public class Address {
    private String address;
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
}

Student.java

public class Student {
    private String name;
    private Address address;
    private String[] book;
    private List<String> hobbys;
    private Map<String, String> card;
    private Set<String> games;
    private Properties info;
    private String wife;
}
  1. beans.xml
  1. 常量注入
<bean id="student" class="com.kuang.pojo.Student">
	<property name="name" value="小明"/>
</bean>
  1. Bean注入
<bean id="addr" class="com.kuang.pojo.Address">
	<property name="address" value="重庆"/>
</bean>
<bean id="student" class="com.kuang.pojo.Student">
	<property name="name" value="小明"/>
	<property name="address" ref="addr"/>
</bean>
  1. 数组注入
<bean id="student" class="com.kuang.pojo.Student">
	<property name="name" value="小明"/>
	<property name="address" ref="addr"/>
	<property name="books">
		<array>
		<value>西游记</value>
		<value>红楼梦</value>
		<value>水浒传</value>
		</array>
	</property>
</bean>
  1. List注入
<property name="hobbys">
	<list>
		<value>听歌</value>
		<value>看电影</value>
		<value>爬山</value>
	</list>
</property>
  1. Map注入
<property name="card">
	<map>
		<entry key="中国邮政" value="456456456465456"/>
		<entry key="建设" value="1456682255511"/>
	</map>
</property>
  1. set注入
<property name="games">
	<set>
		<value>LOL</value>
		<value>BOB</value>
		<value>COC</value>
	</set>
</property>
  1. Null注入
<property name="wife"><null/></property>
  1. Properties注入
<property name="info">
	<props>
		<prop key="学号">20190604</prop>
		<prop key="性别">男</prop>
		<prop key="姓名">小明</prop>
	</props>
</property>
  1. 测试
public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Student student = (Student) context.getBean("student");
        System.out.println(student.getName());
        /*
        Student{
        name='哈哈',
        address=Address{address='xian'},
        book=[11111, 22222, 33333, 44444],
        hobbys=[听歌, 代码, 电影],
        card={身份证=123456789123, 银行卡=98765432132},
        games=[lol, coc, cs],
        info={学号=B16040609, password=root, username=root},
        wife='null'
        }
         */
    }

}

2.3、拓展方式注入

  1. User实体类
public class User {
	private String name;
	private int age;
	public User(String name, int age) {
		this.name=name;
		this.age=age;
	}
	public void setName(String name) {
		this.name = name;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "User{" +
		"name='" + name + '\'' +
		", age=" + age +
		'}';
	}
}
  1. 命名空间注入
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- P命名空间注入,可以直接注入属性的值 property, 属性依然要有set方法 -->
    <bean id="user" class="com.study04.pojo.User" p:name="哈哈" p:age="18"/>
    <!-- C命名空间注入,可以通过构造器注入属性的值  constructor, 属性依然要有set方法   -->
    <bean id="user2" class="com.study04.pojo.User" c:age="18" c:name="呵呵"/>
</beans>
  1. 测试
public void test2() {
    ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
    User user = context.getBean("user2", User.class);
    System.out.println(user);
}

2.4、Bean的作用域

  1. singleton:单例(默认值),每次从容器中get的时候都是同一个对象
<bean id="user2" class="com.study04.pojo.User" scope="singleton"/>
  1. prototype:多例(原型模式),每次从容器中get的时候都会产生一个新对象
<bean id="user2" class="com.study04.pojo.User" scope="prototype"/>
  1. request:作用于web应用的请求范围。表示每个HTTP请求都会有各自的bean实例,一个bean定义对应一个实例
  2. session:作用于web应用的会话。表示在一个HTTP Session中,一个bean定义对应一个实例。
  3. global-session:作用于集群环境的会话范围(全局会话范围),当不是集群范围时,它就是session

request、session、global-session只能在web开发中使用

三、Bean的自动装配

  • 自动装配是Spring满足Bean依赖的一种方式
  • Spring会在上下文中自动寻找,并自动给bean装配属性

在Spring中,有三种装配的方式

  1. 在xml中显示的配置
  2. 在java中显示配置
  3. 隐式的自动装配bean【重要】

Spring的自动装配需要从两个角度来实现,或者说是两个操作:
1. 组件扫描(component scanning):spring会自动发现应用上下文中所创建的bean;
2. 自动装配(autowiring):spring自动满足bean之间的依赖,也就是我们说的IoC/DI;
推荐不使用自动装配xml配置 , 而使用注解。

3.1、测试环境搭建

  1. 新建两个实体类,Cat、Dog 都有一个叫的方法
public class Cat {
    public void shout() {
        System.out.println("miao");
    }
}
public class Dog {
    public void shout() {
        System.out.println("wang");
    }
}
  1. 新建一个用户类
public class User {
	private Cat cat;
	private Dog dog;
	private String str;
}
  1. Spring配置文件
<?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="dog" class="com.kuang.pojo.Dog"/>
	<bean id="cat" class="com.kuang.pojo.Cat"/>
	<bean id="user" class="com.kuang.pojo.User">
		<property name="cat" ref="cat"/>
		<property name="dog" ref="dog"/>
		<property name="str" value="qinjiang"/>
	</bean>
</beans>
  1. 测试
public class MyTest {
@Test
public void testMethodAutowire() {
	ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
	User user = (User) context.getBean("user");
	user.getCat().shout();
	user.getDog().shout();
	}
}

3.2、ByName自动装配

bean id="cat" class="com.study05.pojo.Cat"></bean>
<bean id="dog" class="com.study05.pojo.Dog"></bean>
<!--
byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的 bean Id;
-->
<bean id="people" class="com.study05.pojo.People" autowire="byName">
    <property name="name" value="哈哈哈"></property>
</bean>

小结:
当一个bean节点带有 autowire byName的属性时:

  1. 将查找其类中所有的set方法名,例如setCat,获得将set去掉并且首字母小写的字符串,即cat。
  2. 去spring容器中寻找是否有此字符串名称id的对象。
  3. 如果有,就取出注入;如果没有,就报空指针异常。

3.3、ByType自动装配

<bean id="cat" class="com.study05.pojo.Cat"></bean>
<bean id="dog1" class="com.study05.pojo.Dog"></bean>
<!--
byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean
-->
<bean id="people" class="com.study05.pojo.People" autowire="byType">
    <property name="name" value="哈哈哈"></property>
</bean>

小结:

  • byName的时候,需要保证所有bean的id唯一,且这个bean需要和自动注入的属性的set方法的值一致
  • byType的时候,需要保证所有bean的class唯一,且这个bean需要和自动注入的属性的类型一致

3.4、使用注解实现自动装配

使用注解开发的注意点:

  1. 导入约束:xmlns:context约束
  2. 配置开启注解的支持:context:annotation-config/
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config/>

</beans>

3.4.1、 @Autowired

  • @Autowired是按类型自动转配的,不支持id匹配。
  • 需要导入 spring-aop的包!
  1. 将User类中的set方法去掉,使用@Autowired注解
public class User {
	@Autowired
	private Cat cat;
	@Autowired
	private Dog dog;
	private String str;
	public Cat getCat() {
		return cat;
	}
	public Dog getDog() {
		return dog;
	}
	public String getStr() {
		return str;
	}
}
  1. 此时配置文件内容
<context:annotation-config/>
<bean id="dog" class="com.kuang.pojo.Dog"/>
<bean id="cat" class="com.kuang.pojo.Cat"/>
<bean id="user" class="com.kuang.pojo.User"/>

使用Autowried,可以不再编写set方法了,前提是这个自动装配的属性在IOC容器中存在,且符合名字byName

拓展:
@Autowired(required=false) : false,对象可以为null;true,对象必须存对象,不能为null。

3.4.2、@Qualifier

  • @Autowired是根据类型自动装配的,加上@Qualifier则可以根据byName的方式自动装配
  • @Qualifier不能单独使用。
  1. 配置文件修改内容,保证类型存在对象。且名字不为类的默认名字
<bean id="dog1" class="com.kuang.pojo.Dog"/>
<bean id="dog2" class="com.kuang.pojo.Dog"/>
<bean id="cat1" class="com.kuang.pojo.Cat"/>
<bean id="cat2" class="com.kuang.pojo.Cat"/>
  1. 没有加Qualifier测试,直接报错
  2. 在属性上添加Qualifier注解
@Autowired
@Qualifier(value = "cat2")
private Cat cat;
@Autowired
@Qualifier(value = "dog2")
private Dog dog;

3.4.3、@Resource

  • @Resource如有指定的name属性,先按该属性进行byName方式查找装配;
  • 其次再进行默认的byName方式进行装配
  • 如果以上都不成功,则按byType的方式自动装配。
  • 都不成功,则报异常。
  1. 实体类
public class User {
	//如果允许对象为null,设置required = false,默认为true
	@Resource(name = "cat2")
	private Cat cat;
	@Resource
	private Dog dog;
	private String str;
}
  1. beans.xml
<bean id="dog" class="com.kuang.pojo.Dog"/>
<bean id="cat1" class="com.kuang.pojo.Cat"/>
<bean id="cat2" class="com.kuang.pojo.Cat"/>
<bean id="user" class="com.kuang.pojo.User"/>
  1. 删掉cat2
<bean id="dog" class="com.kuang.pojo.Dog"/>
<bean id="cat1" class="com.kuang.pojo.Cat"/>
  1. 实体类只保留注解
@Resource
private Cat cat;
@Resource
private Dog dog;

结论:先进行byName查找,失败;再进行byType查找,成功。

3.5、小结

@Autowired与@Resource异同:
1、@Autowired与@Resource都可以用来装配bean。都可以写在字段上,或写在setter方法上。
2、@Autowired默认按类型装配(属于spring规范),默认情况下必须要求依赖对象必须存在,如果要允许null 值,可以设置它的required属性为false。如果想使用名称装配可以结合@Qualifier注解进行使用
3、@Resource(属于J2EE复返),默认按照名称进行装配,名称可以通过name属性进行指定。如果没有指定name属性,当注解写在字段上时,默认取字段名进行按照名称查找,如果注解写在setter方法上默认取属性名进行装配。当找不到与名称匹配的bean时才按照类型进行装配。但是需要注意的是,如果name属性一旦指定,就只会按照名称进行装配。
它们的作用相同都是用注解方式注入对象,但执行顺序不同。@Autowired先byType,@Resource先byName。