09 spring基于注解的装配方式

目前为止,都是通过getBean()从容器中获取相应的Bean实例。

容器中Bean的作用域:

  1. singleton:单态模式。即在整个 Spring 容器中,使用 singleton 定义的 Bean 将是单例的,只有一个实例。默认为单态的。
  2. prototype:原型模式。即每次使用 getBean 方法获取的同一个 <bean /> 的实例都是一个新的实例。
  3. request:对于每次 HTTP 请求,都将会产生一个不同的 Bean 实例。
  4. session:对于每个不同的 HTTP session,都将产生一个不同的 Bean 实例。
  5. global session:每个全局的 HTTP session 对应一个 Bean 实例。典型情况下,仅在使用 portlet 集群时有效,多个 Web 应用共享一个 session。一般应用中,global-session 与 session 是等同的。

注:

  1. 对于 scope 的值 request、session 与 global session,只有在 Web 应用中使用 Spring 时,该作用域才有效。
  2. 对于 scope 为 singleton ,该 Bean 是在容器被创建时就被装配好了。
  3. 对于 scope 为 prototype ,Bean 实例是在代码中使用该 Bean 实例时才进行装配的。
  4. 默认为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")

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值