在这篇文章中,我们将讨论在Spring DI和Spring IOC中使用的Spring核心注解。正如我们所知,Spring DI和Spring IOC是Spring框架的核心概念。我们将从org.springframework.beans.factory.annotation
和org.springframework.context.annotation
包中探讨这些Spring核心注解。
我们通常称这些为 "Spring核心注解",我们将在本文中回顾这些注解。
让我们列出所有已知的Spring核心注解。
我们可以使用@Autowired来标记一个Spring将要解析和注入的依赖关系。我们可以在构造器、设置器或字段注入中使用这个注解。
构造函数注入。
@RestController
public class CustomerController {
private CustomerService customerService;
@Autowired
public CustomerController(CustomerService customerService) {
this.customerService = customerService;
}
}
设置器注入。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class CustomerController {
private CustomerService customerService;
@Autowired
public void setCustomerService(CustomerService customerService) {
this.customerService = customerService;
}
}
字段注入。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class CustomerController {
@Autowired
private CustomerService customerService;
}
欲了解更多详情,请访问我们关于@Autowired和Spring中的依赖注入指南的文章。
@Component-annotated
类中使用@Bean注解。import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.companyname.projectname.customer.CustomerService;
import com.companyname.projectname.order.OrderService;
@Configuration
public class Application {
@Bean
public CustomerService customerService() {
return new CustomerService();
}
@Bean
public OrderService orderService() {
return new OrderService();
}
}
前面的配置完全等同于下面的Spring XML。
<beans>
<bean id="customerService" class="com.companyname.projectname.CustomerService"/>
<bean id="orderService" class="com.companyname.projectname.OrderService"/>
</beans>
阅读更多关于@Bean注解的信息:Spring @Bean注解与实例。
这个注解有助于对基于注解的自动布线进行微调。在某些情况下,我们可能会创建多个相同类型的Bean,并希望只将其中一个与某个属性连接起来。这可以使用@Qualifier注解和@Autowired注解来控制。
例子。考虑到EmailService
和SMSService
类实现了单个MessageService
接口。
为多个消息服务的实现创建MessageService
接口。
public interface MessageService {
public void sendMsg(String message);
}
创建实现--EmailService
和SMSService
。
public class EmailService implements MessageService{
public void sendMsg(String message) {
System.out.println(message);
}
}
public class SMSService implements MessageService{
public void sendMsg(String message) {
System.out.println(message);
}
}
是时候看看@Qualifier
注解的用法了。
public interface MessageProcessor {
public void processMsg(String message);
}
public class MessageProcessorImpl implements MessageProcessor {
private MessageService messageService;
// setter based DI
@Autowired
@Qualifier("emailService")
public void setMessageService(MessageService messageService) {
this.messageService = messageService;
}
// constructor based DI
@Autowired
public MessageProcessorImpl(@Qualifier("emailService") MessageService messageService) {
this.messageService = messageService;
}
public void processMsg(String message) {
messageService.sendMsg(message);
}
}
在Spring @Qualifier注解例子中阅读更多关于这个注解的信息。
@Required
注解是方法级注解,适用于Bean的setter方法。
这个注解简单地表明setter方法必须在配置时被配置为依赖注入的值。
例如,@Required
在setter方法上标记我们想通过XML来填充的依赖关系。
@Required
void setColor(String color) {
this.color = color;
}
<bean class="com.javaguides.spring.Car">
<property name="color" value="green" />
</bean>
否则,BeanInitializationException
将被抛出。
###@Value
Spring @Value
注解用于为变量和方法参数分配默认值。我们可以使用@Value注解来读取Spring环境变量以及系统变量。
Spring @Value
注解还支持SpEL。让我们看一下使用@Value注解的一些例子。
**例子:**我们可以使用@Value
注解为类属性指定一个默认值。
@Value("Default DBConfiguration")
private String defaultName;
@Value
注解的参数可以是一个字符串,但Spring试图将其转换为指定类型。下面的代码可以正常工作,并将布尔值和整数值分配给变量。
@Value("true")
private boolean defaultBoolean;
@Value("10")
private int defaultInt;
Spring @Value
- Spring环境属性
@Value("${APP_NAME_NOT_FOUND}")
private String defaultAppName;
使用@Value注解来分配系统变量。
@Value("${java.home}")
private String javaHome;
@Value("${HOME}")
private String homeDir;
Spring @Value - SpEL
@Value("/#{systemProperties['java.home']}")
private String javaHome;
@DependsOn
注解可以强制Spring IoC容器在被@DependsOn
注解的Bean之前初始化一个或多个Bean。
@DependsOn
注解可用于任何直接或间接用@Component
注解的类或用@Bean注解的方法上。
例子。让我们创建FirstBean
和SecondBean
类。在这个例子中,SecondBean
在beanFirstBean
之前被初始化。
public class FirstBean {
@Autowired
private SecondBean secondBean;
}
public class SecondBean {
public SecondBean() {
System.out.println("SecondBean Initialized via Constuctor");
}
}
在基于java的配置类中声明上述Bean
@Configuration
public class AppConfig {
@Bean("firstBean")
@DependsOn(value = {
"secondBean"
})
public FirstBean firstBean() {
return new FirstBean();
}
@Bean("secondBean")
public SecondBean secondBean() {
return new SecondBean();
}
}
阅读更多关于Spring的@DependsOn注解 - @DependsOn注解示例。
默认情况下,Spring IoC容器会在应用程序启动时创建并初始化所有的单子Bean。我们可以通过使用@Lazy
注解来阻止单子Bean的预初始化。
@Lazy
注解可以用在任何直接或间接用@Component
注解的类或用@Bean注解的方法上。
例子。考虑到我们有以下两个Bean--FirstBean
和SecondBean
。在这个例子中,我们将使用@Lazy
注解明确加载FirstBean
。
public class FirstBean {
public void test() {
System.out.println("Method of FirstBean Class");
}
}
public class SecondBean {
public void test() {
System.out.println("Method of SecondBean Class");
}
}
在基于java的配置类中声明上述Bean类。
@Configuration
public class AppConfig {
@Lazy(value = true)
@Bean
public FirstBean firstBean() {
return new FirstBean();
}
@Bean
public SecondBean secondBean() {
return new SecondBean();
}
}
我们可以看到,Bean secondBean是由Spring容器初始化的,而Bean firstBean是显式初始化的。
阅读更多关于@Lazy注解和Spring的完整例子 - @Lazy注解例子。
用@Lookup
注解的方法告诉Spring,当我们调用该方法时要返回该方法的返回类型的实例。
关于注解的详细信息可以在Spring @LookUp Annotation中找到。
当有多个相同类型的Bean时,我们使用@Primary
来给一个Bean更高的优先权。
@Component
@Primary
class Car implements Vehicle {}
@Component
class Bike implements Vehicle {}
@Component
class Driver {
@Autowired
Vehicle vehicle;
}
@Component
class Biker {
@Autowired
@Qualifier("bike")
Vehicle vehicle;
}
在Spring上阅读更多关于这个注解的信息 - @主要注解示例。
###@Scope
我们使用@Scope
来定义@Component
类或@Bean定义的范围。它可以是singleton、prototype、request、session、globalSession或一些自定义的范围。
比如说。
@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)
public class TwitterMessageService implements MessageService {
}
@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class TwitterMessageService implements MessageService {
}
阅读更多关于@Scope注解的内容:Spring @Scope注解与单子范围示例和Spring @Scope注解与原型范围示例。
如果我们希望Spring只在特定的配置文件激活时使用@Component
类或@Bean方法,我们可以用@Profile来标记它。我们可以用注解的值参数来配置配置文件的名称。
@Component
@Profile("sportDay")
class Bike implements Vehicle {}
你可以在这个Spring Profiles中阅读更多关于配置文件的内容。
@Import
注解表示要导入一个或多个@Configuration类。
比如说。在基于Java的配置中,Spring提供了@Import
注解,允许从另一个配置类加载@Bean定义。
@Configuration
public class ConfigA {
@Bean
public A a() {
return new A();
}
}
@Configuration
@Import(ConfigA.class)
public class ConfigB {
@Bean
public B b() {
return new B();
}
}
现在,在实例化上下文时不需要同时指定ConfigA类和ConfigB类,而只需要明确提供ConfigB。
阅读更多关于@Import注解的信息:Spring @Import注解。
Spring提供了一个@ImportResource
注解,用于从applicationContext.xml
文件中加载bean到ApplicationContext。比如说。考虑到我们在classpath上有applicationContext.xml Spring Bean配置的XML文件。
@Configuration
@ImportResource({"classpath/*:applicationContext.xml"})
public class XmlConfiguration {
}
在Spring @ImportResource注解中阅读更多关于这个注解的完整例子。
@PropertySource
注解提供了一种方便的声明机制,用于向Spring的环境中添加PropertySource。要和@Configuration类一起使用。
比如说。在这个例子中,我们从文件config.properties
中读取数据库配置,并使用Environment将这些属性值设置到DataSourceConfig类。
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
@Configuration
@PropertySource("classpath:config.properties")
public class ProperySourceDemo implements InitializingBean {
@Autowired
Environment env;
@Override
public void afterPropertiesSet() throws Exception {
setDatabaseConfig();
}
private void setDatabaseConfig() {
DataSourceConfig config = new DataSourceConfig();
config.setDriver(env.getProperty("jdbc.driver"));
config.setUrl(env.getProperty("jdbc.url"));
config.setUsername(env.getProperty("jdbc.username"));
config.setPassword(env.getProperty("jdbc.password"));
System.out.println(config.toString());
}
}
在Spring @PropertySource Annotation上阅读更多关于这个注解的信息。
我们可以使用这个注解来指定多个@PropertySource
配置。
@PropertySources({
@PropertySource("classpath:config.properties"),
@PropertySource("classpath:db.properties")
})
public class AppConfig {
//...
}
在Spring @PropertySources注解中阅读更多关于此注解的信息。在Spring Core教程中学习完整的Spring Core概念在Spring 5教程中学习Spring框架5。
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.javaguides.net/2018/10/15-spring-core-annotations.html
内容来源于网络,如有侵权,请联系作者删除!