Spring注解配置实现过程的方法
小编给大家分享一下Spring注解配置实现过程的方法,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨吧!
配置注解的支持:
在spring4之后,想要使用注解形式,必须得要引入 aop 的包
<dependency><groupId>org.springframework</groupId><artifactId>spring-aop</artifactId><version>5.2.8.RELEASE</version></dependency>
导入 context 的约束,增加注解的支持:
<?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/></beans>
配置扫描指定包下的注解
<!--指定注解扫描包-->
<context:component-scan base-package="com.lf.pojo"/>
常用注解说明
自动装配注解
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
prototype:多例模式。关闭工厂 ,所有的对象不会销毁。内部的垃圾回收机制会回收
@Controller("user") @Scope("prototype") public class User { @Value("秦疆") public String name; }
看完了这篇文章,相信你对Spring注解配置实现过程的方法有了一定的了解,想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。