简单好看个人主页网站模板网站备案名称更换
2026/3/5 7:19:55 网站建设 项目流程
简单好看个人主页网站模板,网站备案名称更换,电影里的做视频在线观看网站,登封郑州网站建设SpringBoot中**PropertySource、ImportResource、Bean三个注解的用法#xff0c;核心是用它们扩展/替代默认的application配置文件**#xff08;并非直接修改原配置#xff0c;而是补充/自定义配置#xff09;#xff0c;这三个注解解决的是不同场景的配置需求#xff0c…SpringBoot中**PropertySource、ImportResource、Bean三个注解的用法核心是用它们扩展/替代默认的application配置文件**并非直接修改原配置而是补充/自定义配置这三个注解解决的是不同场景的配置需求其中**Bean是SpringBoot最推荐的核心方式**另外两个主要做兼容/配置文件扩展。先明确一个前提SpringBoot默认只自动加载application.properties/yml核心配置文件这三个注解的出现是为了解决默认配置不够用、兼容老Spring配置、纯代码替代配置文件这三类场景所有示例基于基础SpringBoot项目仅引入web依赖即可。一、PropertySource加载自定义的.properties配置文件核心作用专门让Spring加载默认配置文件以外的自定义.properties文件把文件里的keyvalue加载到Spring的环境变量中后续可以通过Value或ConfigurationProperties取值使用。通俗理解SpringBoot默认只认application.properties/yml你想自己建个配置文件比如my-config.properties放业务配置用这个注解告诉Spring把这个文件也加载进来里面的配置我要用到。关键注意默认不支持.yml/yaml文件如需支持yml需自定义配置工厂类实际开发中极少用因此重点讲.properties可指定编码避免中文乱码。注解核心属性value/locations指定自定义配置文件的类路径路径最常用encoding指定文件编码如UTF-8解决中文乱码ignoreResourceNotFound是否忽略文件不存在默认false文件不存在会报错。代码示例PropertySource步骤1创建自定义.properties配置文件在resources目录下新建my-config.properties写入自定义配置# 自定义业务配置 my.user.name张三 my.user.age20 my.user.desc这是自定义配置文件的内容步骤2用PropertySource加载配置文件创建配置类或直接加在主启动类上推荐单独建配置类更规范通过PropertySource加载上述文件importorg.springframework.context.annotation.PropertySource;importorg.springframework.stereotype.Component;// 配置类标识也可用Component效果一致Component// 加载自定义配置文件指定UTF-8编码避免中文乱码PropertySource(valueclasspath:my-config.properties,encodingUTF-8)publicclassMyPropertyConfig{}步骤3读取加载的配置两种常用方式方式1Value 单个取值简单场景用创建Controller注入并测试importorg.springframework.beans.factory.annotation.Value;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RestController;RestControllerpublicclassTestController{// 用Value(${配置key})取值:后是默认值配置不存在时使用Value(${my.user.name:默认名称})privateStringuserName;Value(${my.user.age:18})privateIntegeruserAge;Value(${my.user.desc:无描述})privateStringuserDesc;GetMapping(/test/property)publicStringtestProperty(){return姓名userName年龄userAge描述userDesc;}}方式2ConfigurationProperties 批量绑定推荐适合多配置项创建实体类批量绑定前缀为my.user的配置需加Component让Spring管理importorg.springframework.boot.context.properties.ConfigurationProperties;importorg.springframework.stereotype.Component;// 让Spring管理该类Component// 绑定配置的前缀配置key的公共部分ConfigurationProperties(prefixmy.user)publicclassUserProperties{// 字段名与配置key的后缀一致name对应my.user.nameprivateStringname;privateIntegerage;privateStringdesc;// 生成get/set方法必须否则无法绑定publicStringgetName(){returnname;}publicvoidsetName(Stringname){this.namename;}publicIntegergetAge(){returnage;}publicvoidsetAge(Integerage){this.ageage;}publicStringgetDesc(){returndesc;}publicvoidsetDesc(Stringdesc){this.descdesc;}// 重写toString方便测试OverridepublicStringtoString(){returnUserProperties{namename\, ageage, descdesc\};}}在Controller中注入实体类测试RestControllerpublicclassTestController{// 注入批量绑定的配置实体AutowiredprivateUserPropertiesuserProperties;GetMapping(/test/property/batch)publicStringtestPropertyBatch(){returnuserProperties.toString();}}测试结果启动项目访问http://localhost:8080/test/property和http://localhost:8080/test/property/batch能正常获取到自定义配置文件的内容说明加载成功。二、ImportResource导入传统Spring的xml配置文件核心作用让SpringBoot兼容老的Spring xml配置把xml文件中通过bean标签定义的Bean导入到SpringBoot的IOC容器中让这些Bean被Spring管理并注入使用。通俗理解以前写SSM时会用applicationContext.xml配置bean id class创建Bean现在SpringBoot推荐无xml开发但如果有现成的xml配置不想重写用这个注解告诉Spring把这个xml文件导入进来里面的Bean我还要用。关键注意SpringBoot官方强烈不推荐使用该注解它仅做老项目兼容新项目优先用Bean替代xml配置。注解核心属性locations/value指定xml配置文件的类路径路径最常用name配置集的名称几乎不用。代码示例ImportResource步骤1创建传统Spring xml配置文件在resources目录下新建spring-beans.xml里面用bean定义一个普通Bean比如业务类HelloService?xml version1.0 encodingUTF-8?beansxmlnshttp://www.springframework.org/schema/beansxmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd!-- 传统xml方式定义Beanid是Bean名称class是全类名 --beanidhelloServiceclasscom.example.demo.service.HelloService/bean/beans步骤2创建xml中定义的Bean类新建com.example.demo.service.HelloServicepackagecom.example.demo.service;// 普通类无任何注解因为Bean由xml定义publicclassHelloService{publicStringsayHello(){returnHello! 我是xml配置的Bean;}}步骤3用ImportResource导入xml文件必须加在SpringBoot的主启动类上唯一有效位置指定xml文件路径importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.context.annotation.ImportResource;// 导入xml配置文件让里面的Bean被Spring管理ImportResource(locationsclasspath:spring-beans.xml)SpringBootApplicationpublicclassDemoApplication{publicstaticvoidmain(String[]args){SpringApplication.run(DemoApplication.class,args);}}步骤4注入并测试xml定义的Bean在Controller中注入helloService通过xml的id测试是否能使用RestControllerpublicclassTestController{// 注入xml中定义的BeanAutowiredprivateHelloServicehelloService;GetMapping(/test/xml)publicStringtestXmlBean(){returnhelloService.sayHello();}}测试结果访问http://localhost:8080/test/xml返回Hello! 我是xml配置的Bean说明xml中的Bean被成功加载到Spring容器中。三、Bean纯代码方式创建Spring BeanSpringBoot主推核心作用替代xml中的bean标签在配置类中写方法方法返回一个对象给方法加Bean注解Spring就会把这个返回对象作为Bean放入IOC容器后续可通过Autowired/Resource注入使用。通俗理解不用配置文件、不用xml直接用代码“造对象”并告诉Spring这个对象你帮我管理别人要用直接拿相当于代码版的bean id class。核心搭配Bean必须配合Configuration注解使用Configuration标识的类是SpringBoot的配置类专门用来写Bean方法替代传统的xml配置文件一个项目可以有多个配置类。注解核心属性name/value自定义Bean的名称id数组类型可指定多个别名initMethodBean的初始化方法相当于xml的init-methoddestroyMethodBean的销毁方法相当于xml的destroy-methodprimary设置为主Bean解决同类型多个Bean的注入优先级问题。关键默认规则如果不指定name/valueBean的默认名称是**Bean标注的方法名**。代码示例Bean分2个场景覆盖90%实际开发场景1基础使用——纯代码创建Bean替代xml步骤1创建要被管理的Bean类普通类无注解还是用之前的HelloService无需任何注解packagecom.example.demo.service;publicclassHelloService{publicStringsayHello(){returnHello! 我是Bean配置的Bean;}}步骤2创建配置类用Bean创建Bean新建配置类推荐放在config包下加Configuration写Bean方法importcom.example.demo.service.HelloService;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;// 配置类标识替代传统xml配置文件ConfigurationpublicclassMyBeanConfig{// 方式1默认Bean名称方法名helloServiceBeanpublicHelloServicehelloService(){returnnewHelloService();// 方法返回Bean对象Spring自动管理}// 方式2自定义Bean名称name/value指定可多个别名/* Bean(name {myHelloService, helloService2}) public HelloService helloService() { return new HelloService(); } */}步骤3注入并测试在Controller中注入直接使用默认用方法名注入自定义名称则用名称注入RestControllerpublicclassTestController{// 注入Bean创建的Bean默认方法名helloServiceAutowiredprivateHelloServicehelloService;GetMapping(/test/bean)publicStringtestBean(){returnhelloService.sayHello();}}场景2高级使用——结合自定义配置动态创建Bean实际开发常用把PropertySource加载的自定义配置动态设置到Bean创建的Bean中实现配置驱动Bean这是实际开发中最常用的组合方式。步骤1修改自定义配置文件my-config.properties增加Bean的配置项# 自定义Bean的配置 my.service.name业务服务Bean my.service.versionv1.0步骤2创建带属性的Bean类新建com.example.demo.service.MyService包含属性和set/get方法packagecom.example.demo.service;publicclassMyService{privateStringname;// 服务名称privateStringversion;// 服务版本// 业务方法publicStringgetServiceInfo(){return服务名称name版本version;}// 必须生成set/get方法用于动态赋值publicStringgetName(){returnname;}publicvoidsetName(Stringname){this.namename;}publicStringgetVersion(){returnversion;}publicvoidsetVersion(Stringversion){this.versionversion;}}步骤3配置类中组合PropertySourceBean在配置类中加载自定义配置并用Value取值动态设置到Bean中importcom.example.demo.service.HelloService;importcom.example.demo.service.MyService;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.context.annotation.PropertySource;// 1. 加载自定义配置文件PropertySource(valueclasspath:my-config.properties,encodingUTF-8)// 2. 标识为配置类ConfigurationpublicclassMyBeanConfig{// 3. 从自定义配置中取值Value(${my.service.name})privateStringserviceName;Value(${my.service.version})privateStringserviceVersion;// 4. 动态创建Bean设置配置属性BeanpublicMyServicemyService(){MyServicemyServicenewMyService();myService.setName(serviceName);// 给Bean设置配置值myService.setVersion(serviceVersion);returnmyService;}}步骤4注入并测试动态BeanRestControllerpublicclassTestController{// 注入动态配置的MyServiceAutowiredprivateMyServicemyService;GetMapping(/test/bean/dynamic)publicStringtestDynamicBean(){returnmyService.getServiceInfo();}}测试结果访问http://localhost:8080/test/bean返回Hello! 我是Bean配置的Bean访问http://localhost:8080/test/bean/dynamic返回服务名称业务服务Bean版本v1.0说明Bean被动态配置并成功加载。四、三个注解的核心对比通俗总结为了让你快速区分用表格清晰说明作用、使用场景、推荐程度这是实际开发的核心参考注解核心作用通俗理解主要使用场景SpringBoot推荐程度PropertySource加载自定义.properties配置文件到Spring环境给Spring加“额外的配置文件”配置项太多想分文件管理解耦⭐⭐⭐⭐常用ImportResource导入传统Spring xml配置文件加载xml中的Bean兼容老项目的xml配置老SSM项目迁移到SpringBoot不想重写xml⭐仅兼容用Bean纯代码创建Spring Bean放入IOC容器代码版的bean标签造对象给Spring管理新项目自定义Bean、动态配置Bean、替代xml⭐⭐⭐⭐⭐核心主推五、关键补充知识点Configuration的小细节SpringBoot中配置类加Configuration后默认是单例模式——无论调用多少次Bean方法Spring只会创建一个Bean对象保证容器中Bean的单例性Bean的注入优先级如果同一种类型有多个Bean注入时会报NoUniqueBeanDefinitionException解决方式用Resource(name Bean名称)指定名称注入给其中一个Bean加Primary设置为主BeanSpring会优先注入PropertySource支持yml的坑默认不支持yml如需支持需自定义PropertySourceFactory代码如下了解即可实际开发推荐用.propertiesimportorg.springframework.boot.env.YamlPropertySourceLoader;importorg.springframework.core.env.PropertySource;importorg.springframework.core.io.support.EncodedResource;importorg.springframework.core.io.support.PropertySourceFactory;importjava.io.IOException;importjava.util.List;publicclassYamlPropertySourceFactoryimplementsPropertySourceFactory{OverridepublicPropertySource?createPropertySource(Stringname,EncodedResourceresource)throwsIOException{ListPropertySource?sourcesnewYamlPropertySourceLoader().load(resource.getResource().getFilename(),resource.getResource());returnsources.get(0);}}使用时在PropertySource中指定工厂PropertySource(valueclasspath:my-config.yml,factoryYamlPropertySourceFactory.class,encodingUTF-8)配置类的扫描SpringBoot会自动扫描主启动类所在包及其子包下的Configuration配置类无需额外配置如需扫描外部包用ComponentScan指定包路径。六、总结PropertySource是“加载配置文件”仅负责把自定义.properties的k-v加载到Spring环境本身不创建Bean需配合Value/ConfigurationProperties取值ImportResource是“兼容老xml”仅用于老项目迁移新项目坚决不用是过渡方案Bean是SpringBoot配置的“核心”替代xml和手动new对象可结合PropertySource实现配置驱动Bean是实际开发中自定义Bean的唯一推荐方式三个注解的核心目的都是扩展SpringBoot的默认配置而非修改原application.properties/yml默认配置文件依然是SpringBoot的核心负责框架自身的配置如端口、数据库、日志等。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询