SpringBoot(八)SpringBoot常用注解讲解PropertySource、ImportResource、ConfigurationProperties

本文详细介绍了SpringBoot中@PropertySource用于引入外部配置文件,@ImportResource支持导入传统Spring配置,以及@ConfigurationProperties用于属性绑定的注解。通过实例演示了如何在配置类中整合这些注解进行灵活配置管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SpringBoot(八)SpringBoot常用注解讲解PropertySource、ImportResource、ConfigurationProperties

本文讲解SpringBoot的常用注解

本文记录的是作者的学习过程,供大家参考。如有错误,请大家自行甄别,本文不负责。>_<

1、Spring中的常用核心注解

1.1、常用核心注解

Spring框架有一些常用的注解,添加了这些注解的类会在容器启动时被扫描到,并生成实例加载到Spring的容器中去

常用的注解列表如下:

注解标记描述
@Component通用注解
@Name通用注解
@Respository持久层注解
@Service业务层组件注解
@Controller控制层组件注解

2、SpringBoot的注解

我们在这里画一个图吧:

@SpringBootApplication
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan
@AutoConfigurationPackage
@Import

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

调用流程如下:

AutoConfigurationImportSelector
selectImports
getAutoConfigurationEntry
getCandidateConfigurations
SpringFactoriesLoader.loadFactoryNames
SpringFactoriesLoader.loadSpringFactories
META-INF/spring.factories

最终会读取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修饰的类
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jack_David

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值