Spring 50例常见错误(一)

文章整理来源:Spring编程常见错误50例_spring_spring编程_bean_AOP_SpringCloud_SpringWeb_测试_事务_Data-极客时间

案例1:启动类扫描包路径

        SpringBoot 的 @SpringBootApplication 注解启动类 默认只 扫描此类所在路径下所有的包。

Spring 50例常见错误(一)_第1张图片

         解决:使用添加 @ComponentScan 或 @ComponentScans ,后者可以包含前者,添加多个需要扫描的包

@SpringBootApplication
@ComponentScan("com.spring.puzzle.class1.example1.controller")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

案例2:Bean 中有参构造函数

         在定义 Bean 时,只定义了有参构造函数,下面例子的代码会出现错误:ServiceImpl required a bean of type 'java.lang.String' that could not be found.

@Service
public class ServiceImpl {

    private String serviceName;

    public ServiceImpl(String serviceName){
        this.serviceName = serviceName;
    }

}

        解析:创建 Bean 的步骤有,1.寻找构造器 ; 2. 通过反射调用构造器创建实例

        例子中只给定了一个有参构造器,Spring 会先获取构造器,且构造器中的参数会从 BeanFactory 中获取。而 BeanFactory 中没有确定 serviceName 的 Bean ,故报错。

        解决:在容器中定义名称为 serviceName 的 String Bean

        发现问题:1.不能定义多个有参构造器

                          2.当一个类定义有多个不同名称的 Bean 时,必须指定名称

案例3:原型 Bean 被固定

        定义了一个原型 Bean,并在一个单例 Bean 中进行注入使用,原型 Bean 却成为固定的了

// 定义原型 Bean
@Service
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class ServiceImpl {
}



@RestController
public class HelloWorldController {

    @Autowired
    private ServiceImpl serviceImpl; // 注入 

    @RequestMapping(path = "hi", method = RequestMethod.GET)
    public String hi(){
         return "helloworld, service is : " + serviceImpl;
    };
}

        解决:要想在单例 bean 中,使用非固定的原型 Bean ,不要使用注入的方式,可以使用,1.注入 ApplicationContext 来获取原型 Bean ;2. 使用 @Lookup 注解

你可能感兴趣的:(Spring,spring)