注解的配置格式:

<?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:annotation-config>

如果@Autowired自动装配环境比较复杂,无法通过一个@Autowired完成的时候可以使用@Qualifier(valuer ="dog1") 来配合使用,指定一个对象的注入。

@Autowired和@Resource的区别:

  • 都是通自动装配的,可以放在属性字段上
  • @Autowired通过bytype实现的,并且要求这个对象存在!
  • @Resource默认通过byname实现的,再通过bytype,两个都找不到报错!

执行顺序不同,Autowired通过bytype实现 

 

自动装配注解:

  • @Autowired  : 自动装配通过类型,名字(如果Autowired不能唯一自动装配上的属性,则需要@Qualifier(value="xxx"))
  • @Nullablle : 字段标记了这个注解,说明这个字段可以为null;
  • @Resource :自动装配通过名字,类型
  • @Component :组件,放在类上,说明这个类被Spring管理了,就是bean!
//    @Component 相当于<bean id="User" class="com.kuang.pojo.User"/>
@Component
public class User {
//   @Value 相当于 <property name="name" value="馋虫"/>
    @Value("入鞘还家")
    public String name ;
}

 衍生注解:

@Component 有几个衍生注解,我们在web开发中,会按照mvc三层架构分层

  • dao [@Repository]
  • service[@Service]
  • controller[@Controller]
  • 这四个注解的功能都是一致的,都是将类注册到Spring中,装配Bean。

10.13小结:

xml与注解:

1.xml更加万能,适用于各种场合维护,简单方便。

2.注解不是自己的类使用不了维护相对复杂。

3.注解只负责完成属性注入。

4.我们在使用的过程中,需注意要让注解生效,就需要开启注解的支持。

<!--         指定要扫描的包,这个包下的注解就会生效-->
    <context:component-scan base-package="com.kuang"/>

    <!--    开启注解的支持-->
    <context:annotation-config></context:annotation-config>
posted on 2021-10-12 21:30  比企苦  阅读(21)  评论(0编辑  收藏  举报