Spring 注解教程
Spring Annotations允许我们通过java程序配置依赖项并实现依赖项注入。
目录[ 隐藏 ]
Spring 注解
- Spring框架实现并提升了控制反转(IOC)或依赖注入(DI)的原理,实际上是一个IOC容器。
- 传统上,Spring允许开发人员使用基于XML的配置来管理bean依赖关系。
- 还有另一种方法来定义bean及其依赖项。此方法是基于Java的配置。
- 与XML方法不同,基于Java的配置允许您以编程方式管理bean组件。这就是为什么引入Spring注释的原因。
在本文中,我们将探讨最常用的Spring Annotations,并查看一些示例程序。
Spring注释列表
一些Spring核心框架注释是:
@Configuration:用于指示类声明一个或多个@Bean方法。这些类由Spring容器处理,以在运行时为这些bean生成bean定义和服务请求。@Bean:表示方法生成由Spring容器管理的bean。这是最常用和最重要的弹簧注释之一。@Bean注释也可以与name,initMethod和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并且@PostConstruct是bean initMethod和destroyMethod的替代方法。它可以在我们定义bean类时使用。例如;public class Computer { @PostConstruct public void turnOn(){ System.out.println("Load operating system"); } @PreDestroy public void turnOff(){ System.out.println("Close all programs"); } }@ComponentScan:配置组件扫描指令以与@Configuration类一起使用。在这里,我们可以指定扫描spring组件的基础包。@Component:表示带注释的类是“组件”。当使用基于注释的配置和类路径扫描时,这些类被视为自动检测的候选者。@PropertySource:提供了一个简单的声明机制,用于向Spring的Environment添加属性源。添加属性源文件数组有一个类似的注释,即@PropertySources。@Service:表示带注释的类是“服务”。此注释用作@Component的特化,允许通过类路径扫描自动检测实现类。@Repository:表示带注释的类是“存储库”。此注释用作@Component的特化,并且建议与DAO类一起使用。@Autowired:Spring @Autowired注释用于自动注入bean。Spring @Qualifier注释与Autowired结合使用,以避免在我们为同一类型配置两个bean时出现混淆。
Spring MVC Annotations
一些重要的Spring MVC注释是:
- @Controller
- @RequestMapping
- @PathVariable
- @RequestParam
- @ModelAttribute
- @RequestBody和@ResponseBody
- @RequestHeader和@ResponseHeader
您可以在Spring MVC Tutorial中了解更多相关信息。
Spring Transaction Management Annotations
@Transactional是Spring声明式事务管理注释,在Spring MVC Hibernate上阅读更多内容。
Spring安全注释
@EnableWebSecurity与@Configuration类一起使用以定义Spring Security配置,在Spring Security Example中阅读更多内容。
Spring Boot Annotations
- @SpringBootApplication
- @EnableAutoConfiguration
阅读更多Spring Boot示例。
Spring注释示例
让我们看一个简单的例子,我们将在我们的应用程序中使用Spring注释。下图说明了我的Spring Annotations Example项目。

Spring框架依赖关系
我创建了maven项目并添加了Spring Core Framework依赖项。
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://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>
这将为我们的项目提供所有弹簧核心罐。
组件类
下一步是创建组件类。在这里,我模仿多个数据库组件,一个用于MySQL,另一个用于Oracle。
package com.journaldev.drivers;
public interface DataBaseDriver {
public String getInfo();
}
DataBaseDriver是我们将实现的基本接口。
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注释来指示spring框架将此类视为Component。我们也在使用@PropertySource和@Value注释,Spring将在运行时使用这些来从指定的属性文件中注入和设置这些变量值。下面是mysqldatabase.properties文件中声明的属性。
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 是一个简单的bean,我们将使用服务类为这个bean注入属性。
春季服务类
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注释来指示Spring框架将其视为Service类。然后我们使用@Autowired和@Qualifier("oracleDriver")注释告诉spring框架注入名为oracleDriverclass属性的bean dataBaseDriver。请注意,我们还没有创建这个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。在这个方法中,我们正在从Spring框架中oracledatabase.properties设置为environment变量的文件中读取属性。
这是oracledatabase.properties文件中定义的属性。
db.url=localhost
db.port=4444
db.user=vasiliy
db.password=yilisav
db.driver=driver_name
我们的spring注释示例项目已准备好进行测试。作为总结,我们执行了以下步骤:
- 创建了maven项目并添加了所需的spring依赖项。
- 创建组件类并将资源文件中的属性注入其变量中。
- 如果我们有第三方组件,我们可以使用Service类将依赖项注入其中。就像我们通过UserService类为OracleDriver所做的那样。
- 最后,我们创建了Configuration类来定义spring bean并设置基本包以扫描spring组件类并对其进行配置。
Spring Annotations示例测试
这是我们测试Spring annotations示例项目的主要类。
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 annotations示例项目。
参考:API Doc
524

被折叠的 条评论
为什么被折叠?



