一@Bean

@Bean将类交给spring管理等同于@Component,@Controller,@Service,@Respority

@Bean可以将第三方插件的配置交给spring框架管理

实操:

创建HelloService类

package com.qcby.service; public class HelloService { private String message; public HelloService(String message) { this.message = message; } public void sayHello() { System.out.println(message); } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }

创建配置类AppConfig

@Configuration // 这表明这是一个配置类

public class AppConfig {

@Configuration // 这表明这是一个配置类 public class AppConfig { @Bean public HelloService helloService() { // 使用构造函数创建 HelloService Bean return new HelloService("Hello from HelloService via @Bean!"); } }

启动类

@SpringBootApplication @EnableConfigurationProperties(person.class) @ImportResource("classpath:beans.xml")//导入xml注解 public class mavenSpringBootDemo { public static void main(String[] args) { // SpringApplication.run(mavenSpringBootDemo.class,args); ApplicationContext context = SpringApplication.run(mavenSpringBootDemo.class, args); // // 获取并使用 MyBean // MyBean myBean = context.getBean(MyBean.class); // // // 打印 MyBean 中的消息 // myBean.printMessage(); // 获取 HelloService Bean 并调用其方法 HelloService helloService = context.getBean(HelloService.class); helloService.sayHello(); } }

启动后控制台打印

Hello from HelloService via @Bean!

二@PropertySource

@PropertySource读取加载配置文件:

以前用@ConfigurationProperties告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定;只有这个组件是容器中的组件,才能容器提供的@ConfigurationProperties功能;

@PropertySource可以不仅仅走yml配置文件,可以走别的。

实操

创建person.properties

里面写

person.address.street=TestStreet

删掉yml配置里的street字段,因为要引用person.properties里的

person实体类里加注解

@PropertySource(value = "classpath:person.properties")

启动验证,发现street值已经由yml里的值改为了person.properties里的值。

三@ImportResource

@ImportResource(用的较少)

作用:导入Spring的配置文件,让配置文件里面的内容生效;

Spring Boot里面没有Spring的配置文件,我们自己编写的配置文件,也不能自动识别;

想让Spring的配置文件生效,加载进来;@ImportResource标注在一个配置类上

应用场景:有一处的业务不想和yml配置文件里的东西混着,想单独写一个配置文件,那么就用@ImportResource让其生效

实操

创建MyBean实体类

package com.qcby.model; public class MyBean { private String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public void printMessage() { System.out.println("Message: " + message); } }

创建beans.xml

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-4.3.xsd">

修改配置类

public class mavenSpringBootDemo { public static void main(String[] args) { // SpringApplication.run(mavenSpringBootDemo.class,args); ApplicationContext context = SpringApplication.run(mavenSpringBootDemo.class, args); // 获取并使用 MyBean MyBean myBean = context.getBean(MyBean.class); // 打印 MyBean 中的消息 myBean.printMessage(); } }

启动发现控制台成功打印

Message: Hello from MyBean!

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐