Spring注解方式和注解小结

用于创建对象的4种注解方法
@Component 注解
①在applicationContext.xml引入注解的约束
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"
②在其实现类上添加注解@Component("userService")
相当于在 applicationContext.xml中加入<bean id="" class="">
注解的 value :指定 bean id 。如果不指定 value 属性,默认 bean id 是当前类的类名。首字母小写。
③在applicationContext.xml开启注解扫描
<context:component-scan base-package="实现类的包名"> </context:component-scan>
  @Controller表现层 @Service业务层 @Repository持久层

用于注入数据的
1、@Value
2、@Autowired
3、@Qualifier
4、@Resource
相当于: <property name="" ref="">    
<property name="" value="">
@Value
注入基本类型和string类型的数据
value:用于指定值
@Value ( "张三" ) 给name属性注入值 String类型
@Autowired
给别的类进行注入 如果不存在该类就报错
@Autowired
private UserDao userDao;
@Qualifier
当有多个bean都满足时,优先选择bean的id与属性名一样的进行注入,想指定某个bean 需要在@Autowired后面加@Qualifier("需要指定的bean")
@Autowired
@Qualifier("指定bean的id")
@Resource
直接按照bean的id进行注入 name:指定bean的id,只能注入对象类型
@Resource (name= "指定bean的id" )

用于该表作用域的范围
scope
@Scope("prototype") 调用连两次无参构造

和生命周期相关的
相当于 <bean id="" class="" init-method="" destroy-method=""  />
@PostConstruct在创建IOC对象后立即调用该注解里面的方法进行初始化操作
@PreDestory
满足销毁的条件
IOC对象关闭((ClassPathXmlApplicationContext)applicationContext).close();
作用范围必须是单例@Scope("singleton")


    
    注解小结:
与创建 bean 对象
@Component( id ) 引入约束 通过名称进行注入
@Controller 表示层的注解
@Service 业务层的注解
@Repository 持久层的注解
与注入值相关
@Autowired 给别的类进行注入 给属性进行注入值
@Qualifier 多个 bean 同时满足时选择与类名一样的进行注入  如果需要指定具体的 bean 则需用该注解 按照名称进行注入
@Resource(name= 指定 bean id” )
@Value 注入基本类型和 String 类型的数据   @Value(“ )
与范围相关
@Scope   singleton 单例   prototype 多例 ( 调用两次构造方法在 IOC 对象创建后进行调用 )
与生命周期相关
@PostConstruct IOC 对象创建后调用初始化
@PreDestroy   1.scope 必须是单例   2. 强转 IOC 对象调用 close 方法


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值