Spring使用小技巧--排除bean无法被调用问题

发布于:2024-05-19 ⋅ 阅读:(213) ⋅ 点赞:(0)

我们在项目中可能由于项目的复杂性,创建了个spring的bean,但是调用却出现报错,显示无法找到该bean的异常。

这个时候我们就需要找到出错的原因,很多人往往会忽略的一点就是,你所创建的bean有可能并没有被加载到ioc容器中。但怎么去看这个bean是否被spring装载到了ioc容器呢?

我这里提供一种方法。通过spring上下文获取到beaninition,通过beanName找寻对应的bean是否被加载到ioc,需要注意,您所写的bean,是否为懒加载。

可以在启动时我们自己本地检查,另一种是运行到某个类时,再进行检查。两种方式,各位老爷任选。

废话不多说,直接上代码

启动时检查

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.scheduling.annotation.EnableAsync;

import java.util.Arrays;

@SpringBootApplication
@EnableAsync // springboot 开启异步支持
public class Applications {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(Applications.class, args);
        boolean b = Arrays.stream(context.getBeanDefinitionNames()).anyMatch(a -> {
            // 使用contains是因为,加载到BeanDefinition中的names有可能是全路径
            return a.contains("testController");
        });
        if (b) {
            System.out.println("存在 TestController 的bean");
        }
    }
}

类中检查

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;

@RestController
@Slf4j
public class ProfilesTestController {


    @Autowired
    ConfigurableApplicationContext context;

    @RequestMapping(method = RequestMethod.GET, path = "/profiles/test2")
    public void test2() {
        boolean match = Arrays.stream(context.getBeanDefinitionNames()).anyMatch(a -> {
            return a.contains("testController");
        });
        if (match)  System.out.println("存在 TestController 的bean");;
    }

查看执行结果


网站公告

今日签到

点亮在社区的每一天
去签到