我有一个父母类Car&子类Axio。所以,我试图通过子构造函数中的super(“Axio”)将参数传递给父类中的构造函数参数,然后将该值分配给父类中定义的属性。当我尝试在spring boot中执行应用程序时,它会抛出一个异常陈述
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.
任何人都可以告诉我如何在春季靴子中实现这一目标?我的代码如下,
// Car class
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();
}
}
答案 0 :(得分:0)
正如pvpkiran所评论的那样,如果一个类不是一个Spring bean,你就不能@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();
}
}