SpringBoot(八)SpringBoot常用注解讲解PropertySource、ImportResource、ConfigurationProperties
文章目录
本文讲解SpringBoot的常用注解
本文记录的是作者的学习过程,供大家参考。如有错误,请大家自行甄别,本文不负责。>_<
1、Spring中的常用核心注解
1.1、常用核心注解
Spring框架有一些常用的注解,添加了这些注解的类会在容器启动时被扫描到,并生成实例加载到Spring的容器中去
常用的注解列表如下:
注解标记 | 描述 |
---|---|
@Component | 通用注解 |
@Name | 通用注解 |
@Respository | 持久层注解 |
@Service | 业务层组件注解 |
@Controller | 控制层组件注解 |
2、SpringBoot的注解
我们在这里画一个图吧:
2.1、@SpringBootApplication注解
@SpringBootApplication
标记在SpringBoot主应用程序上的注解,该注解是一个组合注解,是一系列注解的一个组合,其中有三个注解是主要的注解,如下:
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan
如下是一个添加了
@SpringBootApplication
的主程序类
- DemoApplication
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
我们点进去查看
SpringBootApplication
这个注解的代码,会发现该注解是一个组合注解,包含一些元注解信息,和三个SpringBoot的注解
- SpringBootApplication
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
2.2、@SpringBootConfiguration注解
我们点开
@SpringBootConfiguration
注解的代码,如下:可以看到同样也是一个组合注解,但其中最主要的是
@Configuration
注解,表明带有此注解的类是一个配置类
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {
@AliasFor(
annotation = Configuration.class
)
boolean proxyBeanMethods() default true;
}
2.3、@EnableAutoConfiguration注解
我们来查看第二个关键注解:
@EnableAutoConfiguration
,这是一个非常重要的注解,我们直接来查看源码,如下:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
/**
* Environment property that can be used to override when auto-configuration is
* enabled.
*/
String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
/**
* Exclude specific auto-configuration classes such that they will never be applied.
* @return the classes to exclude
*/
Class<?>[] exclude() default {};
/**
* Exclude specific auto-configuration class names such that they will never be
* applied.
* @return the class names to exclude
* @since 1.3.0
*/
String[] excludeName() default {};
}
@EnableAutoConfiguration
我们可以看到,同样的也是一个组合的注解,包含两个重要的注解,分别为:
@AutoConfigurationPackage
@Import
我们一个一个看
2.3.1、@AutoConfigurationPackage
首先找到这个注解
@AutoConfigurationPackage
,源码如下:
@AutoConfigurationPackage
注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import(AutoConfigurationPackages.Registrar.class)
public @interface AutoConfigurationPackage {
/**
* Base packages that should be registered with {@link AutoConfigurationPackages}.
* <p>
* Use {@link #basePackageClasses} for a type-safe alternative to String-based package
* names.
* @return the back package names
* @since 2.3.0
*/
String[] basePackages() default {};
/**
* Type-safe alternative to {@link #basePackages} for specifying the packages to be
* registered with {@link AutoConfigurationPackages}.
* <p>
* Consider creating a special no-op marker class or interface in each package that
* serves no purpose other than being referenced by this attribute.
* @return the base package classes
* @since 2.3.0
*/
Class<?>[] basePackageClasses() default {};
}
这个注解使用
@Import
引入了一个Registrar
注册器,我们查看其源码
- Registrar、PackageImports
static class Registrar implements ImportBeanDefinitionRegistrar, DeterminableImports {
@Override
public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
register(registry, new PackageImports(metadata).getPackageNames().toArray(new String[0]));
}
@Override
public Set<Object> determineImports(AnnotationMetadata metadata) {
return Collections.singleton(new PackageImports(metadata));
}
}
/**
* Wrapper for a package import.
*/
private static final class PackageImports {
private final List<String> packageNames;
PackageImports(AnnotationMetadata metadata) {
AnnotationAttributes attributes = AnnotationAttributes .fromMap(metadata.getAnnotationAttributes(AutoConfigurationPackage.class.getName(), false));
List<String> packageNames = new ArrayList<>();
for (String basePackage : attributes.getStringArray("basePackages")) {
packageNames.add(basePackage);
}
for (Class<?> basePackageClass : attributes.getClassArray("basePackageClasses")) {
packageNames.add(basePackageClass.getPackage().getName());
}
if (packageNames.isEmpty()) {
packageNames.add(ClassUtils.getPackageName(metadata.getClassName()));
}
this.packageNames = Collections.unmodifiableList(packageNames);
}
List<String> getPackageNames() {
return this.packageNames;
}
@Override
public boolean equals(Object obj) {
if (obj == null || getClass() != obj.getClass()) {
return false;
}
return this.packageNames.equals(((PackageImports) obj).packageNames);
}
@Override
public int hashCode() {
return this.packageNames.hashCode();
}
@Override
public String toString() {
return "Package Imports " + this.packageNames;
}
}
我们可以发现,
@AutoConfigurationPackage
注解的主要作用是将 添加该注解的类所在的package 作为 自动配置package 进行管理
2.3.2、@Import
这里我们通过查看
@EnableAutoConfiguration
注解的代码,会发现@Import
注解,这里导入的是一个AutoConfigurationImportSelector
调用流程如下:
最终会读取
spring-boot-autoconfigure-2.3.9.RELEASE.jar
这个jar包中的META-INF/spring.factories
文件,自动加载响应的配置
- META-INF/spring.factories
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\
org.springframework.boot.autoconfigure.context.LifecycleAutoConfiguration,\
org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,\
org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration,\
org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRestClientAutoConfiguration,\
org.springframework.boot.autoconfigure.data.jdbc.JdbcRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.r2dbc.R2dbcDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.r2dbc.R2dbcRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.r2dbc.R2dbcTransactionManagerAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration,\
org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchRestClientAutoConfiguration,\
org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\
org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\
org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,\
org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration,\
org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration,\
org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration,\
org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration,\
org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration,\
org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration,\
org.springframework.boot.autoconfigure.influx.InfluxDbAutoConfiguration,\
org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration,\
org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration,\
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration,\
org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration,\
org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,\
org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\
org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration,\
org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\
org.springframework.boot.autoconfigure.availability.ApplicationAvailabilityAutoConfiguration,\
org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration,\
org.springframework.boot.autoconfigure.ldap.LdapAutoConfiguration,\
org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration,\
org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration,\
org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration,\
org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\
org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration,\
org.springframework.boot.autoconfigure.r2dbc.R2dbcAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketMessagingAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketRequesterAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketServerAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketStrategiesAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration,\
org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.reactive.ReactiveUserDetailsServiceAutoConfiguration,\
org.springframework.boot.autoconfigure.security.rsocket.RSocketSecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.saml2.Saml2RelyingPartyAutoConfiguration,\
org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\
org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.client.reactive.ReactiveOAuth2ClientAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.resource.reactive.ReactiveOAuth2ResourceServerAutoConfiguration,\
org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\
org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration,\
org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration,\
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,\
org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,\
org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration,\
org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration,\
org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.HttpHandlerAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.ReactiveWebServerFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.error.ErrorWebFluxAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.function.client.ClientHttpConnectorAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.reactive.WebSocketReactiveAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.servlet.WebSocketMessagingAutoConfiguration,\
org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration,\
org.springframework.boot.autoconfigure.webservices.client.WebServiceTemplateAutoConfiguration
2.4、@ComponentScan注解
该注解我们可以理解为
<context:component-scan>
标签,在SpringBoot中,我们在
@SpringBootApplication
注解这里可以看到,定义了一些扫描过滤的条件
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
3、与配置相关的注解
3.1、@ConfigurationProperties注解
@ConfigurationProperties
这个注解,一般是用来进行属性绑定使用的,例如,我们有一个实体类Person
该注解一般需要搭配一个Spring的常用核心注解来使用,比如:
@Component
等
prefix
表示绑定的配置的前缀为person
如下:
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
String name;
int age;
boolean boss;
Date birth;
BigDecimal sal;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isBoss() {
return boss;
}
public void setBoss(boolean boss) {
this.boss = boss;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public BigDecimal getSal() {
return sal;
}
public void setSal(BigDecimal sal) {
this.sal = sal;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", boss=" + boss +
", birth=" + birth +
", sal=" + sal +
'}';
}
}
这时,我们可以在application.properties文件中增加相关的配置,Spring容器在启动的过程中,会自动帮我们完成属性的装配
person.name=zhangsan
person.age=18
person.birth=2021/03/20
person.boss=false
person.sal=18000.00
控制台输出r如下:
Person{name='zhangsan', age=18, boss=false, birth=Sat Mar 20 00:00:00 CST 2021, sal=18000.00}
3.2、@PropertySource注解
我们的配置一般放到application.properties文件中,但是这个文件如果配了过多的配置参数的话,会显得非常的臃肿,这时,我们可以将某一类配置单独的放到一个文件中。例如,我们可以在resources目录下新建一个
person.properties
文件,在该文件中配置相关的属性,通过@PropertySource
注解,指定从person.properties
文件中读取配置参数,如下:
- person.properties
person.name=zhangsan
person.age=18
person.birth=2021/03/20
person.boss=false
person.sal=18000.00
- Person
@Component
@PropertySource(value = {"classpath:person.properties"})
@ConfigurationProperties(prefix = "person")
public class Person {
}
3.3、@ImportResource注解
一般来说,我们使用SpringBoot是为了简化配置,删除繁琐的xml配置文件;但是可能存在我们为了兼容老系统,或者针对以前的系统进行升级,避免系统改动量过大,这时需要将以前的配置进行迁移,迁移到我们的SpringBoot项目中。这时需要使用
@ImportResource
注解,标注在我们的配置类上,实现自动加载。
3.3.1、新建一个Service类:StudentInfoService
在com.example.demo.service包下面新建一个类StudentInfoService,代码如下:
package com.example.demo.service;
/**
*
* 用于验证Spring的@ImportResource注解
*
* @author zhang_wei
* @version 1.0.0
* @Classname StudentInfoService
* @Date 2021/3/23 9:14
* @Created by zhang_wei
* @since 1.0.0
*/
public class StudentInfoService {
}
3.3.2、新建一个Spring的配置文件
我们在
resources/conf
目录下新建一个Spring的配置文件student-beans.xml
,在该配置文件中声明一个bean,类型为上面我们新建的StudentInfoService内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 测试@ImportResource注解 -->
<bean id="studentInfoService" class="com.example.demo.service.StudentInfoService"/>
</beans>
3.3.3、在我们的配置类中引入Spring的配置文件
在
com.example.demo.config
包下新建一个配置类MyDemoConfig
,使用@ImportResource
引入我们的Spring配置文件,如下:
package com.example.demo.config;
import com.example.demo.service.HelloService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
/**
* @author zhang_wei
* @version 1.0.0
* @Classname MyDemoConfig
* @Date 2021/3/21 22:36
* @Created by zhang_wei
* @since 1.0.0
*/
@Configuration
@ImportResource(value = {"classpath:conf/student-beans.xml"})
public class MyDemoConfig {
}
3.3.4、启动容器进行验证
在我们的主程序类中,增加如下的验证代码,验证容器中是否存在
boolean isContainStudentInfoService = context.containsBean("studentInfoService");
System.out.println(isContainStudentInfoService);
StudentInfoService studentInfoService = SpringContextUtil.getBean(StudentInfoService.class);
System.out.println(studentInfoService);
启动容器,控制台输出如下,表示没有问题:
true
com.example.demo.service.StudentInfoService@32b22fb4
3.4、@Bean和@Configuration注解
3.4.1、@Bean注解
@Bean
注解,我们可以理解为相当于xml
配置中的bean标签,我们可以在配置类中定义方法,生成bean实例对象,同时SpringBoot容器会扫描到相应的方法,加载实例对象到容器中。要注意:1、
@Bean
注解,默认在容器中生成的beanId为该方法的名称2、也可以通过
@Bean
注解的name
属性,指定在容器中生成beanId我们可以在配置类
MyDemoConfig
中使用@Bean
注解声明一个组件
@Configuration
@ImportResource(value = {"classpath:conf/student-beans.xml"})
public class MyDemoConfig {
@Bean(name = "hello")
public HelloService helloService(){
return new HelloService();
}
}
在我们的主程序中,增加获取该bean的测试代码,如下:
boolean isContainHelloService = context.containsBean("hello");
HelloService helloService = SpringContextUtil.getBean(HelloService.class);
System.out.println(isContainHelloService);
System.out.println(helloService);
运行主程序类,控制台输出如下:
证明我们的注解生效
true
com.example.demo.service.HelloService@39534f94
注意:
- 1、
@Bean
注解一般和@Configuration
注解进行组合使用,这时@Bean
注解相当于xml中的<bean>
标签 - 2、
@Bean
注解可以和@Scope
注解进行搭配使用,实现控制bean的作用域,单例或者原型等
3.4.2、@Configuration注解
@Configuration
注解,带有该注解的类,表示当前的类是一个配置类,其功能相当于xml中的<beans>
标签
注意:
- 1、
@Configuration
注解的类,不能是匿名类 - 2、
@Configuration
注解的类,不能是被final修饰的类