Spring 50例常见错误(一)

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

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

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

         解决:使用添加 @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 注解

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值