@Component
public class MovieRecommender {
private final String catalog;
public MovieRecommender(@Value("${catalog.name}") String catalog) {
this.catalog = catalog;
}
}
@Configuration
@PropertySource(“classpath:application.properties”)
public class AppConfig { }
application.properties file:
catalog.name=MovieCatalog
默认的宽松的内嵌值解析器。它将尝试解析属性值,如果不能解析,属性名(例如${catalog.name})将被注入作为值。
@Configuration
public class AppConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
@Component
public class MovieRecommender {
private final String catalog;
public MovieRecommender(@Value("${catalog.name:defaultCatalog}") String catalog) {
this.catalog = catalog;
}
}
Spring BeanPostProcessor在后台使用一个converonservice来处理将@Value中的字符串值转换为目标类型的过程。如果想为自己的自定义类型提供转换支持,可以提供自己的converonservice bean实例,如下面的示例所示:
@Configuration
public class AppConfig {
@Bean
public ConversionService conversionService() {
DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService();
conversionService.addConverter(new MyCustomConverter());
return conversionService;
}
}
当@Value包含一个SpEL表达式时,该值将在运行时动态计算,如下例所示:
@Component
public class MovieRecommender {
private final String catalog;
public MovieRecommender(@Value("#{systemProperties[‘user.catalog’] + ‘Catalog’ }") String catalog) {
this.catalog = catalog;
}
}
@Component
public class MovieRecommender {
private final Map<String, Integer> countOfMoviesPerCatalog;
public MovieRecommender(
@Value("#{{‘Thriller’: 100, ‘Comedy’: 300}}") Map<String, Integer> countOfMoviesPerCatalog) {
this.countOfMoviesPerCatalog = countOfMoviesPerCatalog;
}
}
如果在Spring ApplicationContext中注册了CommonAnnotationBeanPostProcessor,那么将在生命周期中与相应的Spring生命周期接口方法或显式声明的回调方法相同的点调用携带这些注释之一的方法。在下面的例子中,缓存在初始化时被预填充,在销毁时被清除:
public class CachingMovieLister {
@PostConstruct
public void populateMovieCache() {
// populates the movie cache upon initialization…
}
@PreDestroy
public void clearMovieCache() {
// clears the movie cache upon destruction…
}
}
其他bean注解
@Component和进一步的构造型注解
@Repository注释是任何满足存储库角色或原型(也称为数据访问对象或DAO)的类的标记。该标记的用途之一是异常的自动翻译,如异常翻译中所述。
Spring提供了进一步的原型注释:@Component、@Service和@Controller。
@Component是任何spring管理组件的通用原型。
@Repository、@Service和@Controller是@Component的专门化,用于更特定的用例(分别在持久化、服务和表示层中)。
因此,您可以用@Component来注释组件类,但是通过用@Repository、@Service或@Controller来注释它们,您的类更适合由工具处理或与方面关联。
例如,这些原型注释成为切入点的理想目标。
@Repository、@Service和@Controller还可以在Spring框架的未来版本中携带额外的语义。
因此,如果您正在为您的服务层选择使用@Component还是@Service,那么@Service显然是更好的选择。类似地,如前所述,已经支持@Repository作为持久层中自动异常转换的标记。
组件扫描
@Configuration
@ComponentScan(basePackages = “org.example”)
public class AppConfig {
}
@Configuration
@ComponentScan(basePackages = “org.example”, nameGenerator = MyNameGenerator.class)
public class AppConfig {
}
@Configuration
@ComponentScan(basePackages = “org.example”, scopedProxy = ScopedProxyMode.INTERFACES)
public class AppConfig {
}