Bean的作用域
1、 单例模式
Spring默认就是单例模式
<bean id="user" class="com.tian.pojo.User" p:age="18" p:name="宙斯" scope="singleton"/>
创建的所有实例只有一个
在spring容器开启时创建
在spring容器关闭时销毁!
User user = context.getBean("user", User.class);
User user2 = context.getBean("user", User.class);
System.out.println(user==user2); // true
2、原型模式
<bean id="user" class="com.tian.pojo.User" p:age="18" p:name="宙斯" scope="prototype"/>
每次从容器get时,都会产生一个新对象
User user = context.getBean("user", User.class);
User user2 = context.getBean("user", User.class);
System.out.println(user==user2); // false
3、request,session,application
只能在web开发中使用
scope = "request" // 为每次请求创建
scope = "session" // 为每个会话创建
scope = "application" // 为每个应用程序创建
Bean的自动装配
- 自动装配是Spring满足bean依赖的一种方式
- Spring会在上下文中自动寻找并自动给bean装配属性
- 1、 在xml中显示的配置
- 2、在java中显示的配置
- 3、隐式的自动装配bean【重要】
- @Qualifier = byName 会自动在容器上下文寻找,和自己对象set方法后面值对应的bean id
- @Autowried = byType 会自动在容器上下文寻找,和自己对象属性类型相同的
- @Resource =byName JDK自带的
- @Autowried 引入约束 开启注解的支持 <context:annotation-config/>
- 直接在属性上使用即可!也可以在set上使用
- 使用@Autowried可以不在写set方法,前提是你这个自动装配的属性在IOC(Spring)容器中存在,且符合名字byName ;如果Autowried的属性设置requried = false 表明这个对象可以为null
- @Nullabe 字段表明可以为空
注解开发
添加约束,开启注解支持
<?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
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 扫描指定的包,注解才会生效 -->
<context:component-scan base-package="com.tian.pojo"/>
<!-- 开启注解支持 -->
<context:annotation-config/>
</beans>
1、bean
@Component // 等价于注册了一个bean
public class User {
private int age;
}
2、属性
@Value("18") // property name=“age” value=18
private int age;
3、衍生注解
他们与@Component功能一样,都是被spring托管,只是不同的层级下,我们有一些区分而已
dao层 @Repository
controller层 @Controller
service层 @Service
这个时候,我们的注解扫描应该扫描的是 tian 包下的,controller,service,dao/mapper包,这样子,注解才能生效
<context:component-scan base-package=“com.tian”/>
4、自动装配
- @Qualifier
- @Autowried
- @Resource
5、作用域
@Scope
@Component // 等价于注册了一个bean @Scope("singleton") public class User { @Value("18") // property name=“age” value=18 private int age; }