Spring注解配置实现过程详解

2021-03-06  本文已影响0人  平凡的柚子

配置注解的支持:

在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;  
  } 
}

最新2020整理收集的一些高频面试题(都整理成文档),有很多干货,包含mysql,netty,spring,线程,spring cloud、jvm、源码、算法等详细讲解,也有详细的学习规划图,面试题整理等,需要获取这些内容的朋友请加Q君样:11604713672

上一篇 下一篇

猜你喜欢

热点阅读