小编给大家分享一下Spring注解配置实现过程的方法,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨吧!

配置注解的支持:

在spring4之后,想要使用注解形式,必须得要引入 aop 的包

<dependency><groupId>org.springframework</groupId><artifactId>spring-aop</artifactId><version>5.2.8.RELEASE</version></dependency>

导入 context 的约束,增加注解的支持:

<&#63;xml version="1.0" encoding="UTF-8"&#63;><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/></beans>

配置扫描指定包下的注解

<!--指定注解扫描包-->
<context:component-scan base-package="com.lf.pojo"/>

常用注解说明

自动装配注解

@Autowired:自动装配,其作用是为了消除Java代码中的getter/setter方法和bean中的property属性。其中是否消除getter程序需求,若需要对外提供私有属性,则应当保留@Autowired是按类型自动转配的,不支持id匹配需要导入 spring-aop 包如果@Autowired不能唯一自动装配上属性则需要通过 @Resource(value="xxx")@Quali&#64257;er :如果容器中有一个以上匹配的Bean,则可以通过@Qualifier注解限定Bean的名称@Autowired是根据类型byType自动装配的,若加上@Quali&#64257;er则可以根据byName的方式自动装配@Quali&#64257;er不能单独使用@Resource:自动装配,通过名字,类型。与@Autowired注解作用非常相似@Autowired与@Resource异同总结:@Autowired与@Resource都可以用来装配bean。都可以写在字段上,或写在setter方法上@Autowired默认按类型装配(属于spring规范),默认情况下要求依赖对象必须存在,若要允许null 值,则可以设置它的required属性为false,如:@Autowired(required=false) ,如果想使用名称装配可以结合@Quali&#64257;er注解使用@Resource默认按照名称装配,名称可以通过name属性进行指定。若未指定name属性,当注解位于字段上时,会默认按字段名通过名称查找;若注解写在 setter方法上则默认取属性名进行装配。 当找不到与名称匹配的bean时才按照类型进行装配。但需要注意的是:name属性一旦指定,就只会按照名称进行装配它们的作用相同都是用注解方式注入对象,但执行顺序不同。@Autowired 先 byType,@Resource 先 byName

Bean的实现

@Component:它的作用就是实现bean的注入,@Component 注解可以放在类的上面,但@Component不推荐使用

Spring提供了更加细化的注解形式:@Repository、@Service、@Controller,它们分别对应存储层Bean,业务层 Bean,和展示层Bean。因此推荐使用它们来替代@Component

属性注入

使用注解注入属性

可以不用提供set方法,直接在直接名上添加@value("值")

@Component("user")
// 相当于配置文件中
public class User {
@Value("Java")
// 相当于配置文件中
public String name;
}
```

如果提供了set方法,在set方法上添加@value("值")

@Component("user") public class User { public String name; @Value("Java") public void setName(String name) { this.name = name; } }

衍生注解

@Component的三个衍生注解

为了更好的进行分层,Spring可以使用其它三个注解,其功能一样,都是代表将某个类注册到spring中,装配Bean

@Controller:web层
@Service:service层
@Repository:dao层

作用域

@scope

singleton:默认的,Spring会采用单例模式创建这个对象。关闭工厂 ,所有的对象都会销毁
prototype:多例模式。关闭工厂 ,所有的对象不会销毁。内部的垃圾回收机制会回收

@Controller("user") @Scope("prototype") public class User { @Value("秦疆") public String name; }

看完了这篇文章,相信你对Spring注解配置实现过程的方法有了一定的了解,想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!