1、隐式扫描不到 Bean 的定义(springboot启动类包名里面,扫描控制层无效,因为默认是扫描启动类的包名)
解决:启动类需要加注解
@ComponentScan("com.spring.XXXX.controller")
2、定义的 Bean 缺少隐式依赖
问题:存在两个构造器,都可以调用时,到底应该调用哪个呢?最终 Spring 无从选择,只能尝试去调用默认构造器,而这个默认构造器又不存在,所以测试这个程序它会出错。
Parameter 0 of constructor in com.spring.XXXX.ServiceImpl required a bean of type 'java.lang.String' that could not be found.
解决:
@Servicepublic class ServiceImpl {private String serviceName;public ServiceImpl(String serviceName){this.serviceName = serviceName;}private ServiceImpl(){}public ServiceImpl(String serviceName, String otherStringParameter){this.serviceName = serviceName;}}
3、原型 Bean 被固定(当一个单例的 Bean,使用 @autowired 注解标记其属性时,你一定要注意这个属性值会被固定下来)
错误:
helloworld, service is : com.spring.XXXX.error.ServiceImpl@4908af
解决:使用自动注入 Context或者使用 Lookup 注解
@RestControllerpublic class HelloWorldController {@RequestMapping(path = "hi", method = RequestMethod.GET)public String hi(){return "helloworld, service is : " + getServiceImpl();};@Lookuppublic ServiceImpl getServiceImpl(){return null;}public ServiceImpl getServiceImpl(){return applicationContext.getBean(ServiceImpl.class);}}
4、过多赠予,无所适从
错误:required a single bean, but 2 were found
解决:
