Field XX required a bean of type 使用@componentscan 解决

很少写博客了,似乎就为了让自己不断加深印象来写博客啦~ 

遇到的问题 是 spring boot 启动不起来 问题 是 

Field XXX  that could not be found.

给出的建议Action:

Consider defining a bean of type 'XX ‘ in your configuration.



Spring加载外部Bean两种方式
将定义在另外一个带有@Configuration的类中的Bean加载
1. 在Application类中使用@Import指定该类,
2.让@ComponentScan扫描到该类。


大多数使用的2. 实际上是要在spring boot 初始化前加入该类所在的包 进行扫描

在spring boot 主启动main函数上面加上默认的 扫描就好

@ComponentScan(basePackageClasses = {"XX", "XX.XX"})
这句会将相应的包进行扫描


如果想用自己的注解时可以使用SpringBootApplication 进行中间转化 

自己封装一个启动注解时 

public @interface App {
   
    @AliasFor(annotation = SpringBootApplication.class, attribute = "scanBasePackages")
    String[] scanBasePackages() default {};

    @AliasFor(annotation = SpringBootApplication.class, attribute = "scanBasePackageClasses")
    Class[] scanBasePackageClasses() default {};
}

当然如果就为了这个两个注解就咩有必要封装啦~ 就是启动是如果加入了其余的还要用这个注解时可以这样封装 

要不就直接用

SpringBootApplication


//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.springframework.boot.autoconfigure;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.TypeExcludeFilter;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.core.annotation.AliasFor;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
    Class[] exclude() default {};

    String[] excludeName() default {};

    @AliasFor(
        annotation = ComponentScan.class,
        attribute = "basePackages"
    )
    String[] scanBasePackages() default {};

    @AliasFor(
        annotation = ComponentScan.class,
        attribute = "basePackageClasses"
    )
    Class[] scanBasePackageClasses() default {};
}




你可能感兴趣的:(Field XX required a bean of type 使用@componentscan 解决)