我有一个父类Car和一个子类Axio。因此,我正在尝试通过子构造函数中的super("Axio"(将参数传递给父类中的构造函数参数,然后将值分配给父类中定义的属性。当我尝试在 spring 启动中执行应用程序时,它会向我抛出一个异常,指出
Description:
Field car in com.test.efshop.controller.HelloController required a bean of type 'com.test.efshop.Axio' that could not be found.
Action:
Consider defining a bean of type 'com.test.efshop.Axio' in your configuration.
谁能告诉我如何在春季启动中实现这一目标?我的代码如下,
汽车类
package com.test.efshop;
public class Car {
private String carName;
public String getCarName() {
return carName;
}
public void setCarName(String carName) {
this.carName = carName;
}
public Car(String carName) {
this.carName = carName;
}
public String print() {
return "Car name is : "+carName;
}
}
汽车类的子类,即 Axio
package com.test.efshop;
public class Axio extends Car{
public Axio() {
super("Axio");
}
}
//主方法
package com.test.efshop;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@SpringBootApplication
public class DemoApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
控制器类
package com.test.efshop.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.test.efshop.Axio;
import com.test.efshop.Engine;
@Controller
public class HelloController {
@Autowired
private Axio car;
@RequestMapping(value = "/hello")
public ModelAndView print() {
return new ModelAndView("index");
}
//This is the method which i used to return the value of Car class
@RequestMapping(value = "/hello2")
@ResponseBody
public String print2() {
return car.print();
}
}
正如 pvpkiran 评论的那样,如果一个类不是春豆,你就不能@Autowire
类。
选项 a( 将Axio
类转换为服务或组件。
@Component
public class Axio extends Car {
public Axio() {
super("Axio");
}
}
选项 b( 定义类型 Axio
的 bean。
@SpringBootApplication
public class DemoApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public Axio myAxioBean() {
return new Axio();
}
}