@Autowired
注解@Autowired
是Spring提供的一个注解,用于自动注入Bean。它可以应用于构造函数、字段或setter方法。
构造函数注入:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class MyService {
private final MyRepository repository;
@Autowired
public MyService(MyRepository repository) {
this.repository = repository;
}
}
字段注入:
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class MyService {
@Autowired
private MyRepository repository;
}
Setter方法注入:
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class MyService {
private MyRepository repository;
@Autowired
public void setRepository(MyRepository repository) {
this.repository = repository;
}
}
@Resource
注解@Resource
是JSR-250规范提供的注解,Spring也支持这种注解用于注入Bean。
java
import javax.annotation.Resource;
import org.springframework.stereotype.Component;
@Component
public class MyService {
@Resource
private MyRepository repository;
}
@Inject
注解@Inject
是JSR-330规范提供的注解,Spring支持这种注解用于注入Bean。
java
import javax.inject.Inject;
import org.springframework.stereotype.Component;
@Component
public class MyService {
@Inject
private MyRepository repository;
}
@Qualifier
注解当有多个相同类型的Bean时,可以使用@Qualifier
注解来指定需要注入的具体Bean。
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
@Component
public class MyService {
@Autowired
@Qualifier("specificRepository")
private MyRepository repository;
}
@Primary
注解当有多个相同类型的Bean时,可以使用@Primary
注解来指定一个Bean作为首选Bean。
java
import org.springframework.stereotype.Repository;
@Repository
@Primary
public class PrimaryRepository implements MyRepository {
// ...
}
@Lazy
注解@Lazy
注解可以用于延迟加载Bean,直到第一次使用时才创建Bean实例。
java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.lang.Nullable;
@Component
public class MyService {
@Autowired
@Lazy
private MyRepository repository;
}
@Configuration
和 @Bean
注解在Java配置类中,可以使用@Bean
注解来声明Bean,并将其添加到Spring容器中。
java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyService();
}
}
@Value
注解注入属性值@Value
注解可以用来注入外部配置的值,如properties文件中的值。
java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class MyService {
@Value("${my.property}")
private String myProperty;
}
Spring框架提供了多种灵活的Bean注入方式,包括@Autowired
、@Resource
、@Inject
、@Qualifier
、@Primary
、@Lazy
、@Configuration
、@Bean
和@Value
注解。这些注解使得依赖注入变得简单直观,同时也支持复杂的场景,如处理多个Bean的注入、延迟加载和配置属性注入。选择合适的注入方式可以提高代码的可读性、可维护性和灵活性。了解这些注入方式的适用场景和最佳实践对于开发高效、可扩展的Spring应用至关重要。