Spring中如何使用@Import+@Bean注册Bean呢?
下文笔者讲述不使用@Configuration配置类注册Bean的方法分享
在启动类上使用@import导入类 然后使用@Bean注册Bean例
注解类 package com.java265.annotation; import com.java265.config.MyBeanConfiguration; import org.springframework.context.annotation.Import; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.TYPE) @Retention(RetentionPolicy.Runtime) @Import({MyBeanConfiguration.class}) public @interface EnableMyBean { } 配置类(内部包含Bean) 无需加@Configuration package com.java265.config; import com.java265.entity.MyBean; import org.springframework.context.annotation.Bean; public class MyBeanConfiguration { @Bean public MyBean myBean() { return new MyBean(); } } 导入配置 法1:启动类 启动类上加自定义的注解。 package com.java265; import com.java265.annotation.EnableMyBean; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableAsync; @SpringBootApplication @EnableMyBean public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } 法2:@Configuration 标记的类 package com.java265.config; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.stereotype.Component; @Configuration @Import({MyBeanConfiguration.class}) public class MyBeanImportConfiguration { } 测试 package com.java265.controller; import com.java265.entity.MyBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @Autowired private MyBean myBean; @GetMapping("/test") public String test() { return myBean.sayHello(); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。