首页 > 编程技术 > java

Spring注解配置实现过程详解

发布时间:2020-8-5 13:47

配置注解的支持:

在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

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持猪先飞。

标签:[!--infotagslink--]

您可能感兴趣的文章: