Spring注解允许我们通过java程序配置依赖关系和实现依赖注入。
目录
Spring注解
- Spring框架实现并促进了控制反转(IOC)或依赖注入(DI)的原理,实际上是一个IOC容器。
- 传统上,Spring允许开发人员使用基于XML的配置来管理bean依赖关系。
- 有一种定义bean及其依赖关系的替代方法。此方法是基于Java的配置。
- 与XML方法不同,基于Java的配置允许您以编程方式管理bean组件。这就是为什么引入Spring注解。
在本文中,我们将探讨最常用的Spring注解,并查看一些示例程序。
Spring注解列表
一些spring核心框架注解是:
@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.@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"); } }
@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"); } }
@ComponentScan
: Configures component scanning directives for use with @Configuration classes. Here we can specify the base packages to scan for spring components.@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.@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
.@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.@Repository
: Indicates that an annotated class is a “Repository”. This annotation serves as a specialization of @Component and advisable to use with 刀类。@Autowired
: Spring@Autowired注解用于豆子的自动注射。Spring@Qualifier注解与Autowired一起使用,以避免当我们为同一类型配置了两个以上的bean时出现混淆。
Spring MVC注解
一些重要的Spring MVC注解包括:
- @控制器
- @请求映射
- @路径变量
- @请求参数
- @模型属性
- @RequestBody和@ResponseBody
- @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引导注解
- @SpringBoot应用程序
- @启用自动配置
更多信息请访问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注解示例项目已经准备好进行测试了。总之,我们执行了以下步骤:
- 创建了maven项目并添加了必需的spring依赖项。
- 创建组件类,并将资源文件中的属性注入到它的变量中。
- 如果我们有第三方组件,我们可以使用服务类将依赖项注入其中。就像我们通过UserService类为OracleDriver所做的那样。
- 最后,我们创建了配置类来定义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文件