Spring 框架入门教程
1. 1. Spring 框架 2. 2. Spring 5 3. 3. Spring WebFlux 4. 4. 先介绍一下 Spring 5. 5. 什么是 Spring 依赖注入 6. 6. 什么是 Spring IoC 容器 和 Bean 7. 7. Spring Bean 的生命周期 8. 8. Spring REST 开发 9. 9. Spring REST XML 10. 10. Spring RestTemplate 开发 11. 11. Spring AOP 切面编程 12. 12. Spring AOP 方法调优 13. 13. Spring 注解详解 14. 14. Spring 核心注解之 @Autowired 15. 15. Spring 核心注解之 @RequestMapping 16. 16. Spring MVC 开发样例 17. 17. Spring MVC 开发指南 18. 18. Spring MVC 异常处理机制 19. 19. Spring MVC Validator 20. 20. Spring MVC 拦截器 21. 21. Spring MVC 文件上传 22. 22. Spring MVC 国际化(i18n) 23. 23. Spring MVC Hibernate MqSQL 24. 24. Spring ORM 25. 25. Spring ORM JPA 26. 26. Spring Data JPA 27. 27. Spring 事务管理 28. 28. 常用的 Spring JdbcTemplate 29. 29. Spring Security 简介 30. 30. Spring Security 教程 31. 31. Spring Security UserDetailsService 32. 32. Spring MVC 登录注销简单案例 33. 33. Spring Security Roles 34. 34. Spring Boot Tutorial 35. 35. Spring Boot Components 36. 36. Spring Boot CLI Hello World 37. 37. Spring Boot Initilizr Web 38. 38. Spring Boot Initilizr IDE 39. 39. Spring Boot Initilizr CLI 40. 40. Spring Boot Initilizr Tools 41. 41. Spring Boot MongoDB 42. 42. Spring Boot Redis Cache 43. 43. Spring Boot 常见面试问题 44. 44. Spring Batch 45. 45. Spring Batch 批处理示例 46. 46. Spring AMQP 47. 47. Spring RabbitMQ 48. 48. Spring AMQP RabbitMQ 49. 49. Apache ActiveMQ 安装与启动 50. 50. Spring ActiveMQ 教程 51. 51. Spring ActiveMQ 示例 52. 52. Spring JDBC 53. 53. Spring DataSource JNDI 54. 54. Spring Hibernate 55. 55. Spring Primefaces JPA 56. 56. Spring Primefaces MongoDB 57. 57. Spring Primefaces Hibernate 58. 58. SpringRoo Primefaces Hibernate 59. 59. Spring JSF 60. 60. Spring JDF Hibernate 61. 61. Spring Data MongoDB 62. 62. Spring 常见面试问题

13. Spring 注解详解

Spring注解允许我们通过java程序配置依赖关系和实现依赖注入。

Spring注解

  • Spring框架实现并促进了控制反转(IOC)或依赖注入(DI)的原理,实际上是一个IOC容器。
  • 传统上,Spring允许开发人员使用基于XML的配置来管理bean依赖关系。
  • 有一种定义bean及其依赖关系的替代方法。此方法是基于Java的配置。
  • 与XML方法不同,基于Java的配置允许您以编程方式管理bean组件。这就是为什么引入Spring注解。

在本文中,我们将探讨最常用的Spring注解,并查看一些示例程序。

Spring注解列表

一些spring核心框架注解是:

  1. @Configuration: Used to indicate that a class declares one or more @Bean methods. These classes are processed by the Spring container to generate bean definitions and service requests for those beans at runtime.
  2. @Bean: Indicates that a method produces a bean to be managed by the Spring container. This is one of the most used and important spring annotation. @Bean annotation also can be used with parameters like name, initMethod and destroyMethod.
    • name–允许您为bean命名
    • initMethod–允许您选择将在上下文寄存器上调用的方法
    • destroyMethod–允许您选择在上下文关闭时调用的方法

    例如:

    
    @Configuration
    public class AppConfig {
    
        @Bean(name = "comp", initMethod = "turnOn", destroyMethod = "turnOff")
        Computer computer(){
            return new Computer();
        }
    }
    
    
    public class Computer {
    
        public void turnOn(){
            System.out.println("Load operating system");
        }
        public void turnOff(){
            System.out.println("Close all programs");
        }
    }
    
  3. @PreDestroy and @PostConstruct are alternative way for bean initMethod and destroyMethod. It can be used when the bean class is defined by us. For example;
    
     public class Computer {
    
        @PostConstruct
        public void turnOn(){
            System.out.println("Load operating system");
        }
    
        @PreDestroy
        public void turnOff(){
            System.out.println("Close all programs");
        }
    }
    
  4. @ComponentScan: Configures component scanning directives for use with @Configuration classes. Here we can specify the base packages to scan for spring components.
  5. @Component: Indicates that an annotated class is a “component”. Such classes are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning.
  6. @PropertySource: provides a simple declarative mechanism for adding a property source to Spring’s Environment. There is a similar annotation for adding an array of property source files i.e @PropertySources.
  7. @Service: Indicates that an annotated class is a “Service”. This annotation serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning.
  8. @Repository: Indicates that an annotated class is a “Repository”. This annotation serves as a specialization of @Component and advisable to use with 类。
  9. @Autowired: Spring@Autowired注解用于豆子的自动注射。Spring@Qualifier注解与Autowired一起使用,以避免当我们为同一类型配置了两个以上的bean时出现混淆。

Spring MVC注解

一些重要的Spring MVC注解包括:

  1. @控制器
  2. @请求映射
  3. @路径变量
  4. @请求参数
  5. @模型属性
  6. @RequestBody和@ResponseBody
  7. @RequestHeader和@ResponseHeader

您可以在SpringMVC教程.

Spring事务管理注解

@Transactional is the spring declarative transaction management annotation, read more at SpringMVCHibernate.

Spring安全注解

@EnableWebSecurity is used with @Configuration class to have the Spring Security configuration defined, read more at Spring Security示例.

Spring引导注解

  1. @SpringBoot应用程序
  2. @启用自动配置

更多信息请访问Spring Boot示例.

Spring注解示例

让我们看一个简单的例子,我们将在应用程序中使用Spring注解。下图说明了我的Spring注解示例项目。

Spring框架依赖项

我已经创建了maven项目并添加了Spring核心框架依赖项。


<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.journaldev.spring</groupId>
	<artifactId>spring-annotations</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>Spring Annotations</name>

	<properties>
		<spring.framework>4.3.0.RELEASE</spring.framework>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.framework}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.framework}</version>
		</dependency>

	</dependencies>

</project>

这将为我们的项目提供所有的spring核心jar。

组件类

下一步是创建组件类。这里我模拟了多个数据库组件,一个用于MySQL,另一个用于Oracle。


package com.journaldev.drivers;

public interface DataBaseDriver {
    public String getInfo();
}

DataBaseDriver is the base 接口我们将实施。


package com.journaldev.drivers;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource("classpath:mysqldatabase.properties")
public class MySqlDriver implements DataBaseDriver {

    @Value("${databaseName}")
    private String databaseName;
    @Value("${disableStatementPooling}")
    private String disableStatementPooling;

    public String getInfo() {
        return "[ Driver: mySql" +
                ", databaseName: " + databaseName +
                ", disableStatementPooling: " + disableStatementPooling +
                " ]";
    }
}

注意使用@Component annotation to indicate spring framework to treat this class as a Component. We are also using @PropertySource and @Value annotations, Spring will use these at runtime to inject and set these variable values from specified property file. Below is the properties declared in mysqldatabase.properties file.


databaseName=school
disableStatementPooling=true

package com.journaldev.drivers;

public class OracleDriver implements DataBaseDriver {

    protected String url;
    protected String user;
    protected String password;
    protected String driver;
    protected Integer port;


    public String getUrl() {
        return url;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getDriver() {
        return driver;
    }

    public void setDriver(String driver) {
        this.driver = driver;
    }

    public Integer getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getInfo() {
        return "[ Driver: Oracle" +
                ", url: " + url +
                ", port; " + port +
                ", user: " + user +
                ", password: " + password  +
                ", driver: " + driver +
                " ] ";
    }
}

OracleDriver is a simple bean, we will use service class to inject properties to this bean.

Spring服务班


package com.journaldev.service;

import com.journaldev.drivers.DataBaseDriver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Autowired
    @Qualifier("oracleDriver")
    private DataBaseDriver dataBaseDriver;

    public String getDriverInfo(){
        return dataBaseDriver.getInfo();
    }
}

我们正在使用@Service annotation to indicate Spring framework to treat this as a Service class. Then we are using @Autowired and @Qualifier("oracleDriver") annotations to tell spring framework to inject bean named oracleDriver to class property dataBaseDriver. Note that we haven’t yet created this spring bean.

Spring Bean

最后一步是创建我们的Spring Bean和配置类,将所有的东西粘在一起。


package com.journaldev.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

import com.journaldev.drivers.DataBaseDriver;
import com.journaldev.drivers.MySqlDriver;
import com.journaldev.drivers.OracleDriver;

@Configuration
@ComponentScan("com.journaldev")
@PropertySource("classpath:oracledatabase.properties")
public class AppConfig {

	@Autowired
        Environment environment;
	
	@Bean
	DataBaseDriver oracleDriver() {
        OracleDriver oracleDriver = new OracleDriver();
	oracleDriver.setDriver(environment.getProperty("db.driver"));
        oracleDriver.setUrl(environment.getProperty("db.url"));
        oracleDriver.setPort(Integer.parseInt(environment.getProperty("db.port")));
        oracleDriver.setUser(environment.getProperty("db.user"));
        oracleDriver.setPassword(environment.getProperty("db.password"));

        return oracleDriver;

	}

	@Bean
	DataBaseDriver mysqlDriver() {
		return new MySqlDriver();
	}
}

注意的bean定义oracleDriver. In this method, we are reading properties from oracledatabase.properties file that is being set to environment variable by Spring framework.

以下是中定义的属性oracledatabase.properties file.


db.url=localhost
db.port=4444
db.user=vasiliy
db.password=yilisav
db.driver=driver_name

我们的spring注解示例项目已经准备好进行测试了。总之,我们执行了以下步骤:

  1. 创建了maven项目并添加了必需的spring依赖项。
  2. 创建组件类,并将资源文件中的属性注入到它的变量中。
  3. 如果我们有第三方组件,我们可以使用服务类将依赖项注入其中。就像我们通过UserService类为OracleDriver所做的那样。
  4. 最后,我们创建了配置类来定义Spring Bean并将基本包设置为扫描spring组件类并配置它们。

Spring注解示例测试

下面是测试Spring注解示例项目的主类。


package com.journaldev;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;

import com.journaldev.config.AppConfig;
import com.journaldev.drivers.DataBaseDriver;
import com.journaldev.service.UserService;

public class Main {
	public static void main(String[] args) {
	AbstractApplicationContext appContext = new AnnotationConfigApplicationContext(AppConfig.class);

	DataBaseDriver oracle = appContext.getBean("oracleDriver", DataBaseDriver.class);
	DataBaseDriver mysql = appContext.getBean("mysqlDriver", DataBaseDriver.class);
		
        System.out.println("Oracle driver info:");
        System.out.println(oracle.getInfo());
        
        System.out.println("MySQL driver info:");
        System.out.println(mysql.getInfo());

        System.out.println("UserService Information");
	UserService userService = appContext.getBean(UserService.class);
	System.out.println(userService.getDriverInfo());

	appContext.close();
	}
}

下图显示了产生的输出。注意,我们还没有配置任何日志框架,因此所有spring框架日志都以红色打印到控制台中。

以上是对spring注解的简要介绍。我在这里列出了大多数重要的注解,但是对于特定的任务,还有很多注解。您可以从下面的链接下载我的spring注解示例项目。

参考文献:API文件