5 Spring配置
5.1 别名
<!-- 设置别名:在获取Bean的时候,可以通过别名获取-->
<alias name="user" alias="userName" />
<bean id="user" class="com.serene.pojo.User">
<constructor-arg name="name" value="剑诛心" />
</bean>
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
User user = (User)context.getBean("userName");
user.show();
}
5.2 Bean的配置
<!--
id:bean 的唯一标识符,也就是相当于我们学的对象名
class:bean 对象对应的全限定名字:包名+类型
name:也就是别名,可设置多个别名,使用逗号、分号、空格隔开
-->
<bean id="userT" class="com.serene.pojo.UserT" name="t t1; t2, t3">
<property name="name" value="剑咫尺" />
</bean>
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserT user = (UserT)context.getBean("t");
user.show();
}
如果不配置id和name,可以根据 **applicationContext.getBean(UserT.class)获取对象 **
<bean class="com.serene.pojo.UserT" >
<property name="name" value="剑咫尺" />
</bean>
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//UserT user = (UserT)context.getBean("t");
UserT user = context.getBean(UserT.class);
user.show();
}
5.3 import
该import,一般用于团队开发使用,他可以将多个配置文件,导入合并为一个
假设我们有三个人开发,不同的类需要注册在不同的bean中,我们可以利用import将所有人的beans.xml合并为一个总的!
三个不同的人写的不同的beans.xml文件:
beans1.xml
beans2.xml
beans3.xml
我们可在标准配置文件**(applicationContext.xml)**中写上:
<!-- applicationContext.xml -->
<import resource="beans1.xml"/>
<import resource="beans2.xml"/>
<import resource="beans3.xml"/>
使用的时候直接使用总的配置就可以了!
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
6 依赖注入
6.1 构造器注入
前面介绍过了,参考4.IOC创建对象的方式
6.2 Set方式注入【重点】
- 依赖注入:Set注入
- 依赖:bean对象的创建依赖于容器!
- 注入:bean对象的所有属性,由容器来注入!
【环境搭建】
1.复杂类型
public class Address {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
2.真实测试对象
public class Student {
private String name;
private Address address;
private String[] books;
private List<String> hobbies;
private Map<String, String> card;
private Set<String> games;
private String wife;
private Properties info;
//此处省略了get、set方法
}
3.beans.xml
<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="student" class="com.serene.pojo.Student">
<!--1.普通值注入,value-->
<property name="name" value="韵宝宝"/>
</bean>
</beans>
4.测试程序
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student st = (Student)context.getBean("student");
System.out.println(st.getName());
}
}
5.完善容器中的注入信息
<!--也注入地址类-->
<bean id="address" class="com.serene.pojo.Address">
<property name="address" value="盛世归园"/>
</bean>
<bean id="student" class="com.serene.pojo.Student">
<!--1.普通值注入,value-->
<property name="name" value="韵宝宝"/>
<!--2.bean注入,ref-->
<property name="address" ref="address"/>
<!--3.数组注入,array-value-->
<property name="books">
<array>
<value>神雕侠侣</value>
<value>射雕英雄传</value>
<value>天龙八部</value>
<value>倚天屠龙记</value>
</array>
</property>
<!--4.list注入,list-value-->
<property name="hobbies">
<list>
<value>唱</value>
<value>跳</value>
<value>rap</value>
<value>打篮球</value>
</list>
</property>
<!--4.Map注入,map-entry(key-value)-->
<property name="card">
<map>
<entry key="身份证" value="365214499506158452" />
<entry key="银行卡" value="32514455244665211" />
</map>
</property>
<!-- 5.Set注入,set-value-->
<property name="games">
<set>
<value>DNF</value>
<value>LOL</value>
<value>CF</value>
</set>
</property>
<!--6.null值注入,null-->
<property name="wife">
<null/>
</property>
<!--7.Properies注入,props-prop(key)-->
<property name="info">
<props>
<prop key="driver">mysqlhost</prop>
<prop key="url">192.168.4.75</prop>
<prop key="name">root</prop>
<prop key="password">987654321</prop>
</props>
</property>
</bean>
同时也完善测试代码
public class Student {
private String name;
private Address address;
private String[] books;
private List<String> hobbies;
private Map<String, String> card;
private Set<String> games;
private String wife;
private Properties info;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' + '\n' +
", address=" + address.toString() +'\n' +
", books=" + Arrays.toString(books) +'\n' +
", hobbies=" + hobbies +'\n' +
", card=" + card +'\n' +
", games=" + games +'\n' +
", wife='" + wife + '\'' +'\n' +
", info=" + info +
'}';
}
//此处省略了get、set方法
}
//测试代码
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student st = (Student)context.getBean("student");
Address ad = (Address)context.getBean("address");
System.out.println(ad.getAddress());
System.out.println(st.toString());
}
}
打印结果如下:
6.3 拓展方式注入
我们可以使用p命名空间和c命名空间进行注入,新建文件userbean.xml
<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">
</beans>
在使用的时候需要在容器中导入xml约束:
<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.(注意上面添加的p命名标签)-->
<bean id="user" class="com.serene.pojo.User" p:name="剑非道" p:age="20"/>
<!--c命名空间注入,通过构造器注入:constructor-args.(注意上面添加的p命名标签)-->
<bean id="user1" class="com.serene.pojo.User" c:age="18" c:name="剑咫尺"/>
</beans>
//新建的对象类User
public class User {
private String name;
private int age;
//有参构造和无参构造在测试c标签需要使用到,需要加上
public User() {
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
//测试代码
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("userbean.xml");
User user = context.getBean("user", User.class);
User user1 = context.getBean("user1", User.class);
System.out.println(user);
System.out.println(user1);
}
6.4 bean的作用域
1.单例模式(Spring默认使用的机制)
<bean id="user1" class="com.serene.pojo.User" c:age="18" c:name="剑咫尺" scope="singleton"/>
<!-- 注意上面的scope="singleton" 不写默认为单例模式-->
修改6.3的测试代码如下:
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("userbean.xml");
User user = context.getBean("user", User.class);
User user1 = context.getBean("user1", User.class);
System.out.println(user==user1);
/*System.out.println(user);
System.out.println(user1);*/
}
最后输出为true,虽然创建了两个对象,但是两个对象实质是同一个。
2.原型模式:每次从容器中get对象的时候,都会从新产生一个新的对象。
<bean id="user1" class="com.serene.pojo.User" c:age="18" c:name="剑咫尺" scope="prototype"/>
此时1中的测试代码就会输出为false。
3.其余的request、session、application,这些只能在wab开发中使用到!遇到再看。
对应练习代码为spring-04-di
7 Bean的自动装配
- 自动装配是Spring满足bean依赖一种方式!
- Spring会在上下文中自动寻找,并自动给bean装配属性!
在Spring中有三种装配的方式:
1.在xml中显示的配置;
2.在java中显示配置;
3.隐式的自动装配bean【重要】
7.1 测试环境搭建
环境搭建:创建项目,一个人有两个宠物!
三个实体类:
//宠物1猫
public class Cat {
public void shot(){
System.out.println("wang!");
}
}
//宠物2狗
public class Dog {
public void shot(){
System.out.println("miao!");
}
}
//主人
public class Person {
private String name;
private Cat cat;
private Dog dog;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Cat getCat() {
return cat;
}
public void setCat(Cat cat) {
this.cat = cat;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", cat=" + cat +
", dog=" + dog +
'}';
}
}
容器代码,手动注入属性:
<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="cat" class="com.serene.pojo.Cat"/>
<bean id="dog" class="com.serene.pojo.Dog"/>
<bean id="person" class="com.serene.pojo.Person">
<property name="name" value="韵宝宝"/>
<property name="cat" ref="cat"/>
<property name="dog" ref="dog"/>
</bean>
</beans>
测试代码:
public class MyTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Person ps = context.getBean("person", Person.class);
ps.getCat().shot();
ps.getDog().shot();
}
}
7.2 ByName自动装填
<bean id="cat" class="com.serene.pojo.Cat"/>
<bean id="dog" class="com.serene.pojo.Dog"/>
<!--
byName:会自动在容器上下文查找,和自己对象set方法后面的值对应的bean id!
-->
<bean id="person" class="com.serene.pojo.Person" autowire="byName">
<property name="name" value="韵宝宝"/>
<!--<property name="cat" ref="cat"/>
<property name="dog" ref="dog"/>-->
</bean>
如上面的容器中,person对象中的cat和dog类,不用再手动配置,直接使用autowire=byName
7.3 ByType自动装填
<bean id="cat1" class="com.serene.pojo.Cat"/>
<bean id="dog1" class="com.serene.pojo.Dog"/>
<!--
byType:会自动在容器上下文总查找,和自己对象属性类型(class)相同的bean!
-->
<bean id="person" class="com.serene.pojo.Person" autowire="byType">
<property name="name" value="剑非道"/>
</bean>
如上面的容器,只需要保证需求的对象class是正确的就可以,甚至可以取消id属性。
小结:
- 使用ByName的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致!
- 使用ByType的时候,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致!
7.4 使用注解实现自动装配
jdk1.5支持的注解,Spring2.5就支持注解了!
要使用注解须知:
-
导入约束
<!--2中context相关--> xmlns:context="http://www.springframework.org/schema/context" http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"
-
配置注解的支持
<?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>
@Autowired
容器中不再对bean装配属性
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" 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 http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"> <!--开启注解的支持 --> <context:annotation-config /> <bean id="cat" class="com.serene.pojo.Cat"/> <bean id="dog" class="com.serene.pojo.Dog"/> <bean id="person" class="com.serene.pojo.Person" /> </beans>
直接在属性上使用即可!也可以在set方法上使用!
public class Person { private String name; @Autowired private Cat cat; @Autowired private Dog dog; public String getName() { return name; } public void setName(String name) { this.name = name; } public Cat getCat() { return cat; } public Dog getDog() { return dog; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", cat=" + cat + ", dog=" + dog + '}'; } }
使用Autowired我们就可以不用编写set方法了,前提是你这个自动配置的属性在IOC(Spring)容器中存在,且符合名字ByName!
科普:
// @Nullable 字段标记了这个注解,说明这个字段可以为null
public void setName(@Nullable String name) {
this.name = name;
}
// 点开@Autowired可以看到,有个required属性可以设置一个boolean值
public @interface Autowired {
boolean required() default true;
}
测试如下:
public class Person {
private String name;
//如果显示定义了Autowired的required属性为false,说明这个对象可以为null,否则不允许为空,为空会报错。
@Autowired(required = false)
private Cat cat;
@Autowired
private Dog dog;
}
如果通过@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成时,如同下面的情况,有多个对象的时候:
<bean id="cat1" class="com.serene.pojo.Cat"/>
<bean id="cat2" class="com.serene.pojo.Cat"/>
<bean id="dog1" class="com.serene.pojo.Dog"/>
<bean id="dog2" class="com.serene.pojo.Dog"/>
<bean id="person" class="com.serene.pojo.Person" />
我们可以使用 @Qualifier(value = “xxx”)去配置@Autowired的使用,指定一个唯一的bean对象注入!
public class Person {
private String name;
@Autowired(required = false)
@Qualifier(value = "cat1")
private Cat cat;
@Autowired
@Qualifier(value = "dog1")
private Dog dog;
}
@Resource
public class Person {
private String name;
@Resource(name = "cat1")
private Cat cat;
@Resource
private Dog dog;
}
<!-- <bean id="cat1" class="com.serene.pojo.Cat"/>-->
<bean id="cat2" class="com.serene.pojo.Cat"/>
<!-- <bean id="dog1" class="com.serene.pojo.Dog"/>-->
<bean id="dog2" class="com.serene.pojo.Dog"/>
<bean id="person" class="com.serene.pojo.Person" />
使用该中注解时,需要保证,当id能够装配时,容器中可以有多个同类对象;当id不能装配时,只能有一个同类对象存在,但是可以通过配置Resource的值来完成装配,可以存在多个同类对象。
小结:
@Resource和@Autowired的区别:
- 都是用来实现自动装配的,都可以放在属性字段的上
- @Autowired通过ByType的方式实现,而且必须要求这个对象存在!【常用】
- @Resource默认通过ByName的方式实现,如果找不到名字,则通过ByType实现!如果两个都找不到的情况下,就报错!【常用】
- 执行顺序不同:
- @Autowired通过ByType的方式实现!
- @Resource默认通过ByName的方式实现
- 类型重复的话,如果名字不是默认的(如cat11,cat2,不是默认的cat),
- @Autowired配合@Qualiifier(value=“cat11”)使用
- @Resource直接使用@Resource(name=“cat11”)
对应练习代码:spring-05-auto