HelloSpring
一、配置元数据
1、基于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">
<!--使用spring来创建对象,在spring中,这些都称为Bean-->
<bean id="user" class="com.xbh.pojo.User">
<property name="name" value="qianqian"/>
<!--value:具体的值,基本数据类型-->
<!--ref:引用Spring容器中创建好的对象-->
</bean>
</beans>
- 该id属性是标识单个bean定义的字符串。
- 该class属性定义Bean的类型并使用完全限定的类名。
1、Spring之前创对象的方式
类型 变量名 =new 类型();
2、在Spring中不在使用new关键字创建对象,而是使用< bean>标签
id=变量名
class=new的对象
property相当于给对象中的属性设置一个值
可以看出来,这个创对象的过程就实现了控制反转,使用Spring之后,对象的管理、控制都交给了spring的IOC容器来管理,这样子就改变了传统应用程序是由程序本身创建控制、管理的!总而言之,到了现在,我们彻底的不用再程序中去改动,实现不同的操作,只需要在xml配置文件中进行修改。
二、实例化容器
org.springframework.beans和org.springframework.context包是Spring框架的IOC容器的基础。
public class UserTest {
@Test
public void test(){
//获取Spring的容器
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//我们的对象现在都在spring中管理了,如果我们要使用,直接从里边取出即可
User user = (User) context.getBean("user");
System.out.println(user.toString());
}
}
输出结果:User{name='qianqian'}
- 那么Spring是如何将属性注入的呢,底层最根本的就是通过set方法进行注入
- Spring庞大的体系
在配置文件加载的时候,容器中管理的对象就已经初始化了,所以,不论getBean几次,得到的都是同一个对象
三、探讨IOC是如何创建对象的
1、通过无参构造器创建对象
User user = (User) context.getBean("user");
可见我们在getBean的时候,就创建了对象
控制台输出----User的无参构造器被调用了
2、通过有参构造器创建对象
2.1、方式一:下标赋值
<bean id="user" class="com.xbh.pojo.User">
<constructor-arg index="0" value="倩倩"/>
</bean>
控制台输出----User{name='倩倩'}
2.2、方式二:通过类型创建(不建议使用)
<bean id="user" class="com.xbh.pojo.User">
<constructor-arg type="java.lang.String" value="我爱倩倩"/>
</bean>
控制台输出----User{name='我爱倩倩'}
值得注意的是,基本类型可以直接使用,但是引用类型必须使用全限定名
2.3、方式三:直接通过参数名设置(推荐)
<bean id="user" class="com.xbh.pojo.User">
<constructor-arg name="name" value="倩倩真好看"/>
</bean>
控制台输出----User{name='倩倩真好看'}
四、Spring配置
4.1、alias别名
<bean id="user" class="com.xbh.pojo.User">
<constructor-arg name="name" value="倩倩真好看"/>
</bean>
<alias name="user" alias="user2"/>
控制台输出----User{name='倩倩真好看'}
User user = (User) context.getBean("user2");
System.out.println(user.toString());
4.2、Bean的配置
- id属性是标识单个bean定义的字符串。
- class属性定义Bean的类型并使用完全限定的类名。
- name属性也可以取别名,而且更高级,可以同时取多个别名
4.3、import
import一般用于团队开发使用,他可以将多个配置文件导入合并成一个总的配置文件
<beans>
<import resource="services.xml"/>
<import resource="resources/messageSource.xml"/>
<import resource="/resources/themeSource.xml"/>
</beans>
五、DI依赖注入
5.1、构造器注入
5.2、Set注入【重点】
-
依赖:bean对象的创建依赖于容器!
-
注入:bean对象中的所有属性都由容器注入
-
配置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="address" class="com.xbh.pojo.Address"></bean>
<bean id="student" class="com.xbh.pojo.Student">
<!-- 1、普通值注入:value-->
<property name="name" value="许宝华"/>
<!-- 2、Bean注入:ref-->
<property name="address" ref="address"/>
<!-- 3、数组注入-->
<property name="books" >
<array>
<value>红楼梦</value>
<value>西游记</value>
<value>水浒传</value>
</array>
</property>
<!-- 4、list注入-->
<property name="hobby" >
<list>
<value>听歌</value>
<value>看电影</value>
<value>打篮球</value>
</list>
</property>
<!-- 5、Map注入-->
<property name="card">
<map>
<entry key="1" value="1的值"/>
<entry key="2" value="2的值"/>
<entry key="3" value="3的值"/>
</map>
</property>
<!-- 6、Set注入-->
<property name="games">
<set>
<value>LOL</value>
<value>CS</value>
</set>
</property>
<!-- 7、空值注入-->
<property name="wife" >
<null/>
</property>
<!-- 8、Properties-->
<property name="info">
<props>
<prop key="学号">2050412523</prop>
<prop key="性别">男</prop>
</props>
</property>
</bean>
</beans>
- 测试
@Test
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student student =(Student) context.getBean("student");
System.out.println("普通值注入"+student.getName());
System.out.println("Bean注入"+student.getAddress());
System.out.println("数组注入"+student.getBooks());
System.out.println("List注入"+student.getHobby());
System.out.println("Map注入"+student.getCard());
System.out.println("Set注入"+student.getGames());
System.out.println("空值注入"+student.getWife());
System.out.println("Properties配置类注入"+student.getInfo());
System.out.println(student.toString());
}
- 测试结果
普通值注入许宝华
Bean注入com.xbh.pojo.Address@44f75083
数组注入[Ljava.lang.String;@2698dc7
List注入[听歌, 看电影, 打篮球]
Map注入{1=1的值, 2=2的值, 3=3的值}
Set注入[LOL, CS]
空值注入null
Properties配置类注入{学号=2050412523, 性别=男}
5.3、扩展方式注入
- p标签:
xmlns:p="http://www.springframework.org/schema/p"
p命名空间注入,可以直接注入属性的值
p命名空间注入对应着Set的属性注入
<bean id="user" class="com.xbh.pojo.User" p:name="倩倩真好看"/>
注意: p命名空间不如标准XML格式灵活。例如,用于声明属性引用的格式与以结尾的属性发生冲突Ref,而标准XML格式则没有。我们建议您谨慎选择方法,并将其传达给团队成员,以避免同时使用这三种方法生成XML文档。
- c标签
xmlns:c="http://www.springframework.org/schema/c"
<bean id="user" class="com.xbh.pojo.User" c:name="倩倩真美丽"/>
c命名空间注入对应着构造器注入
六、Bean的作用域
6.1、singleton单例模式
在配置文件加载的时候,容器中管理的对象就已经初始化了,所以,不论getBean几次,得到的都是同一个对象
6.2、prototype原型模式
每次从容器中get的时候,都会产生一个新对象
<bean id="accountService" class="com.something.DefaultAccountService" scope="prototype"/>
6.3、其他的request、session、application等只能在web开发中使用
七、Bean的自动装配
- 自动装配是Spring满足的bean依赖的一种方式,Spring会在上下文中自动寻找,并自动给bean装配属性!
7.1、在xml中显示的配置
7.2、在java中显示的配置
7.3、隐式的自动装配bean【重点】
7.3.1、byName自动装配
- byName:会自动在容器上下文中查找,和自己对象的set方法后面的值对应的beanid
<bean id="user" class="com.xbh.pojo.User" autowire="byName">
<property name="name" value="倩倩"/>
</bean>
<bean id="address" class="com.xbh.pojo.Address"></bean>
- 测试
@Test
public void test(){
//获取Spring的上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//我们的对象现在都在spring中管理了,如果我们要使用,直接从里边取出即可
User user = context.getBean("user",User.class);
user.getAddress().show();
System.out.println(user.toString());
}
控制台输出我在家在中国 User{name='倩倩', address=com.xbh.pojo.Address@52525845}
可见控制台的输出内容,完成了自动装配,由于User内部有setAddress()方法,然后会在上下文中找符合set方法后面的值对应的id,如果满足,则进行自动装配
7.3.2、bytype自动装配
- byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean
注意:
1.byname的时候,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致
2.bytype时候,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性类型一致
7.3.3、使用注解实现自动装配
- 要使用注解须知:
- 1.导入约束: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>
-
在bean中为需要自动装配的属性加上注解
-
@Autowired
:【常用】直接在属性上使用即可,也可以在set方法上使用
使用@Autowired我们可以不在编写Set方法了,前提是你这个自动装配的属性在IOC(Spring)容器中存在,且符合名字byname
public class User {
private String name;
@Autowired
private Address address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
@Autowired
public void setAddress(Address address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", address=" + address +
'}';
}
}
-
@Qualifier(value=“xxx”)
:如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候,我们可以使用@Qualifier(value=“xxx”)去配合@Autowired的使用,指定一个唯一的bean对象注入 -
@Resource
:java原生的注解import javax.annotation.Resource
Resource会先通过id查找,如果查找不到在通过类型查找,如果依然查不到的话,则会报错
@Resource和@Autowired的区别
1.都是用来自动装配的,都可以放在属性字段上
2.@Autowired通过byType的方式实现,而且必须要求这个对象存在!【常用】
3.@Resource默认通过byname的方式实现,如果找不到名字,则通过byType实现,如果两个都找不到,则会报错【常用】
八、Spring注解开发【重点】
使用注解须知:
1、在Spring4之后,要使用注解开发,必须要保证aop的包的导入
2、使用注解需要导入context约束,增加注解的支持
<?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:component-scan base-package="com.xbh.pojo"/>
<context:annotation-config/>
</beans>
8.1、@Component
@Component:组件,放在类上,说明这个类被Spring管理了,即bean!
@Component
public class User {
private String name="666";
}
@Component等价于< bean id=“user” class=“com.xbh.pojo.User”/>
- 测试
@Test
public void test3(){
ApplicationContext context = new ClassPathXmlApplicationContext("newBeans.xml");
User user = context.getBean("user", User.class);
System.out.println(user.name);
}
控制台输出666
8.1、@Value
@Value:属性注入
@Component
public class User {
@Value("倩倩真好看")
private String name;
//也可以放在set方法上
@Value("倩倩真好看")
public void setName(String name) {
this.name = name;
}
}
@Value等价于< property name=“name” value=“倩倩真好看”/>
- 测试
@Test
public void test3(){
ApplicationContext context = new ClassPathXmlApplicationContext("newBeans.xml");
User user = context.getBean("user", User.class);
System.out.println(user.getName());
}
控制台输出:倩倩真好看
8.3、衍生的注解
@Component有几个衍生注解。我们在web开发中,会按照mvc三层架构分层!
- dao【@Repository】
- service【@Service】
- controller【@Controller】
这四个注解功能一样,都是代表将某个类注册到Spring中,装配Bean!
8.4、自动装配
- @Autowired
- @Nullable:字段标记了这个注解,说明这个字段可以为null。
- @Resource
8.5、作用域【@Scope】
- singleton:单例模式
@Scope("singleton")
- prototype:原型模式
@Scope("prototype")
8.6、xml与注解区别
- xml更加万能,适用于任何场合!维护简单方便
- 注解不是自己的类不可以使用,维护相对复杂
最佳实践:
1、xml用来管理bean
2、注解只负责完成属性的注入
3、值得注意的是,在使用注解之前一定要让注解生效,必须开启注解的支持
九、使用java的方式配置Spring【重点】
完全不使用Spring的xml配置,全权交给Java来做,JavaConfig是Spring的一个子项目,在Spring4之后,他成为了一个核心功能
- 1、创建一个config类
@Configuration代表这是一个配置类,等价于beans.xml,代表着他可以干beans.xml里能干的所有事
@Configuration也会被Spring容器托管,注册到容器中,因为他本来就是一个@Component
@Bean注册一个bean,等价于一个bean标签,这个方法的名字的就相当于bean标签的id属性,这个方法的返回值,相当于bean标签的class属性
@Configuration
@ComponentScan("com.xbh.pojo")
@Import(TeacherConfig2.class)
public class TeacherConfig {
@Bean
public Teacher getTeacher(){
return new Teacher();
}
}
- 2、让实体类实现自动装配
@Component:当前类被Spring接管了,注册到了容器中
//@Component:当前类被Spring接管了,注册到了容器中
@Component
public class Teacher {
private String name;
@Override
public String toString() {
return "Teacher{" +
"name='" + name + '\'' +
'}';
}
public String getName() {
return name;
}
@Value("王倩")
public void setName(String name) {
this.name = name;
}
}
- 3、测试
@Test
public void test4(){
ApplicationContext context = new AnnotationConfigApplicationContext(TeacherConfig.class);
Teacher teacher = context.getBean("getTeacher", Teacher.class);
System.out.println(teacher.toString());
}
控制台输出结果:Teacher{name='王倩'}
这种纯Java的配置方式,在SpringBoot中随处可见
参考秦疆老师的笔记