spring注解

spring可以使用xml和注解的方式注入beans。而注解有很多,下面会介绍一些有用的注解

@ComponentScan

如果全都使用注解,不参杂一点xml,可以建立一个配置类ApplicationConfig,然后使用@ComponentScan来配置扫描目录中含有注解的,然后将它注入到容器中。

但建议使用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">

    <!-- 设定Spring 去哪些包中找Annotation -->
    <context:component-scan base-package="org.example"/>

</beans>

​

参考:1.10.3. Automatically detecting classes and registering bean definitions

@Component

将被注解的类加入到容器中

@Autowired

可以声明构造函数、属性、setter方法,声明后,容器根据参数类型将所需的对象将被注入进来。不能注解简单类型的属性

参考:Spring @Autowired Annotation

@Value

可以为简单类型的属性注入值。

@Primary

在使用@Autowired的时候,如果被注解的属性是一个接口,而接口的实现类有多个,那么容器就不知道该使用哪个实现类注入进来。那么使用@Primary在某个实现类上时,这个类会被优先使用被注入。

@Qualifier

上述问题也可以使用@Qualifier来解决,通过此注解指定具体的name属性值,将按名称的方式注入。

参考:Spring @Qualifier Annotation

@Resource

和@Autowired类似,不过是通过name名称来注入对象

参考:Spring JSR-250 Annotations

@Required

被注释的方法必须要注入

参考:Spring @Required Annotation

@Configuration &@Bean

@Component只能注解在类上,而@Bean可以注解在方法上,该方法返回的bean将被装配到容器中。bean的name即为函数名,类型为放回值的类型。被注解的方法的类需要被@Configuration注解。

@Service & @Repository @Controller

与@Component并无什么区别,只是含有语义信息而已。

 

 

总的参考:

spring 学习之四(spring的注入方式(xml和annotation)

Spring的Annotation支持

Part 1: Spring Annotations

spring beans源码解读之--Bean的注解(annotation)

08-spring学习-annotation配置

Java Web基础——Action+Service +Dao三层的功能划分

Spring Tutorial

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值