目前为止,都是通过getBean()从容器中获取相应的Bean实例。
容器中Bean的作用域:
- singleton:单态模式。即在整个 Spring 容器中,使用 singleton 定义的 Bean 将是单例的,只有一个实例。默认为单态的。
- prototype:原型模式。即每次使用 getBean 方法获取的同一个
<bean />
的实例都是一个新的实例。 - request:对于每次 HTTP 请求,都将会产生一个不同的 Bean 实例。
- session:对于每个不同的 HTTP session,都将产生一个不同的 Bean 实例。
- global session:每个全局的 HTTP session 对应一个 Bean 实例。典型情况下,仅在使用 portlet 集群时有效,多个 Web 应用共享一个 session。一般应用中,global-session 与 session 是等同的。
注:
- 对于 scope 的值 request、session 与 global session,只有在 Web 应用中使用 Spring 时,该作用域才有效。
- 对于 scope 为 singleton ,该 Bean 是在容器被创建时就被装配好了。
- 对于 scope 为 prototype ,Bean 实例是在代码中使用该 Bean 实例时才进行装配的。
- 默认为singleton
基于注解的装配方式
不需要在spring配置文件中声明Bean实例。
spring-context.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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
">
<context:annotation-config />
<context:component-scan base-package="com.funtl.leeshop"/>
</beans>
然后在类上使用注解声明Bean就可以咯
spring注解
声明Bean:
@Repository 对DAO进行注解
@Service 对Service注解
@Controller 对Controller注解
@Component 对除了以上三种的其他类注解
注解的 value 属性用于指定该 bean 的 id 值
@Scope用于指定作用域
@scope("prototype")
装配Bean
@Autowired 按类型自动装配
@Resource 忧郁哥name属性,指定bean
@Resource(name = "userService")