Spring中如何使用@Import+@Bean注册Bean呢?

重生 Spring 发布时间:2024-02-18 21:51:24 阅读数:4947 1
下文笔者讲述不使用@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();
    }
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaFramework/Spring/202402/7982.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者