Java 没有可用类型的合格bean
线程“main”org.springframework.beans.factory.NoSuchBeanDefinitionException中的异常:没有类型为“com.spring.dto.Car2”的合格bean可用Java 没有可用类型的合格bean,java,spring,autowired,Java,Spring,Autowired,线程“main”org.springframework.beans.factory.NoSuchBeanDefinitionException中的异常:没有类型为“com.spring.dto.Car2”的合格bean可用 Controller.java- public class Controller { public static void main(String[] args) { ConfigurableApplicationContext context = new Cla
Controller.java-
public class Controller {
public static void main(String[] args) {
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("configu.xml");
Car2 c2 = (Car2) context.getBean(Car2.class);
System.out.println(c2);
}
}
Car2.java-
@ToString @Component
public class Car2 {
@Autowired
private Engine engine;
}
Engine.java-
@Setter @ToString
public class Engine {
private String modelYear;
}
configu.xml-
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.spring.dto.Car2" />
<context:annotation-config />
<bean class="com.spring.dto.Engine">
<property name="modelYear" value="2015"></property>
</bean>
</beans>
请忽略注释@ToString和@Setter-为了简单起见,我使用Lombok项目。我认为错误在这里:
<context:component-scan base-package="com.spring.dto.Car2" />
值应该是包,而不是类。将其更改为“com.spring.dto”,那么它应该可以工作。我认为错误在这里:
<context:component-scan base-package="com.spring.dto.Car2" />
值应该是包,而不是类。将其更改为“com.spring.dto”,那么它应该可以工作。也用组件注释引擎类。欢迎使用SO,请阅读。@SangamBelose他有一个Bean定义,这是他的xml,您应该使用:
config.xml中的基本包应该是基本包,也就是说,您拥有所有您希望spring实例化的类,正如Sangam正确指出的那样..也用@Component注释您的引擎类,因此,它可以用于自动布线,也可以使用组件注释引擎类。欢迎使用so,请阅读。@SangamBelose他有一个Bean定义,这是他应该使用的xml:
config.xml中的基本包应该是基本包,也就是说,从你的所有类中,你都希望spring实例化,正如Sangam正确指出的那样..也用@Component注释你的引擎类,所以它可以用于自动连接