类上加@Component报错No qualifying bean of type ‘XXX‘ available另一种解决方案

时间:2025-01-26 09:45:52

开发了一个构建类, 里面基本都是静态方法, 先需要注入service层进来, 查询数据库, 然而类上加@Componen后, 启动报错

: Error creating bean with name 'buildCepCodePattern' defined in file [XXX\]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is : No qualifying bean of type '' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
	at (:799) ~[spring-beans-5.2.:5.2.]
	at (:228) ~[spring-beans-5.2.:5.2.]
	at (:1361) ~[spring-beans-5.2.:5.2.]
	at (:1208) ~[spring-beans-5.2.:5.2.]
	at (:556) ~[spring-beans-5.2.:5.2.]
	at (:516) ~[spring-beans-5.2.:5.2.]
	at $doGetBean$0(:324) ~[spring-beans-5.2.:5.2.]
	at (:234) ~[spring-beans-5.2.:5.2.]
	at (:322) ~[spring-beans-5.2.:5.2.]
	at (:202) ~[spring-beans-5.2.:5.2.]
	at (:897) ~[spring-beans-5.2.:5.2.]
	at (:879) ~[spring-context-5.2.:5.2.]
	at (:551) ~[spring-context-5.2.:5.2.]
	at (:143) ~[spring-boot-2.3.:2.3.]
	at (:755) ~[spring-boot-2.3.:2.3.]
	at (:747) ~[spring-boot-2.3.:2.3.]
	at (:402) ~[spring-boot-2.3.:2.3.]
	at (:312) ~[spring-boot-2.3.:2.3.]
	at (:140) ~[spring-boot-2.3.:2.3.]
	at (:33) [:?]
Caused by: : No qualifying bean of type '' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
	at (:1717) ~[spring-beans-5.2.:5.2.]
	at (:1273) ~[spring-beans-5.2.:5.2.]
	at (:1227) ~[spring-beans-5.2.:5.2.]
	at (:886) ~[spring-beans-5.2.:5.2.]
	at (:790) ~[spring-beans-5.2.:5.2.]
	... 19 more

排查了下, 没有解决@Compone的问题, 故使用其它的方式, 我们需要的是在这个类里注入一个xxxService, 所以可以这样做:

@Service
public class XxxService extends BaseService<Xxx> implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
         = applicationContext;
    }

    public static XxxService getBean() {
        return ();
    }
}

使用的时候直接 XxxService .getBean().xxx即可