Spring之注解开发详解

Spring注解开发

1、环境配置

导入约束

<?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:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       https://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/aop
       https://www.springframework.org/schema/aop/spring-aop.xsd">
    
    !--去将指定包下的注解加入xml中配置-->
    <context:component-scan base-package="com.tx"/>
    <!--开启注解-->
    <context:annotation-config/>
</beans>

2、属性注入

前提:bean中开启了<context:component-scan base-package=“com.tx”/>,他会去扫描com.tx包下的注解加入xml中

 @Value("tanx")
private String name;

3、衍生注解(组件)

@Component】有几个衍生注解,按照MVC的架构分层,分别给不同层不同的注册注解,但效果都是一样的。

@Server】:Service(业务层) 用于在IOC容器中注册

@Controller】:Controller(控制层)用于在IOC容器中注册

@Repository】:dao(数据访问层、持久层)用于在IOC容器中注册

4、自动装配置

@Autowired(一般放在属性上面,也可以放在set方法上面)

  • 按byType自动注入,先匹配类型(class),存在的类型唯一,id无论是否正确,都可以匹配。
  • 类型不唯一则匹配id,但只要class不匹配,id匹配也错误。

Qualifier(value)

  • 在有多个相同的class类型时,且id不和属性名相同时,value可以指定id
<bean id="cat111" class="com.tx.pojo.Cat"/>
<bean id="cat222" class="com.tx.pojo.Cat"/>
@Autowired
@Qualifier(value = "cat111")
private Cat cat;

@Resource(一般放在属性名上,同时也可以放在set方法上)

  • 按byName自动注入,在id名不相同时,可以使用name指定id
  • 在属性名上使用注解,去掉set方法也可以正常使用。
<bean id="dog1" class="com.tx.pojo.Dog"/>
<bean id="dog2" class="com.tx.pojo.Dog"/>
@Resource(name = "dog2")
private Dog dog;

@Autowired和@Resource:

相同点:

  • 都是用来进行自动注入的,都可以放在属性字段和set方法上。

不同点:

  • 【@Autowired】是通过byType注入。【常用】
  • 【@Resource】是通过byName注入,但是当类型只有一个且id不同,则会通过byType进行注入,都找不到则报错。

5、作用域

@Scope

@Component
@Scope("singleton")	//设置作用域
public class User {
    @Value("tanx")
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

6、小结

xml和注解:

  • xml:更加万能,可以处理更加复杂的操作,适用于任何场所,维护简单方便。

  • 注解:有局限性(非本类不能使用),维护相对复杂。

最佳实践:

  • xml用来管理bean,注解用来完成属性的注入。
发布了67 篇原创文章 · 获赞 0 · 访问量 2451

猜你喜欢

转载自blog.csdn.net/sabstarb/article/details/105307888