Java Springboot,使用Rest控制器从对象访问字段
在使用Springboot创建API以及理解Bean如何工作方面有点困难 我有三门课,我尽可能地简化了它们 甲级 应用 控制器 我的问题是,在控制器中,我没有从创建的ClassA对象myClass中获取所需的VAR,实际上我不确定我得到了什么 我也尝试过这样做,结果相似Java Springboot,使用Rest控制器从对象访问字段,java,spring-boot,Java,Spring Boot,在使用Springboot创建API以及理解Bean如何工作方面有点困难 我有三门课,我尽可能地简化了它们 甲级 应用 控制器 我的问题是,在控制器中,我没有从创建的ClassA对象myClass中获取所需的VAR,实际上我不确定我得到了什么 我也尝试过这样做,结果相似 @SpringBootApplication public class Application { private static ClassA myClass; private static variable m
@SpringBootApplication
public class Application
{
private static ClassA myClass;
private static variable myNeededVar;
@Bean
public variable getNeededVar()
{
return myNeededVar;
}
public static void main( String[] args )
{
myClass = new ClassA();
myNeededVar = myClass.getNeededVar();
ClassA.start();
SpringApplication.run( Application.class, args );
}
}
如果有人能为我指出正确的方向,将应用程序中实例化的ClassA中的所需VAR放入我的rest控制器(以及随后我将创建的所有其他控制器),那将非常感谢
谢谢 - 弹簧的工作方式并不完全符合您的预期。你
应该将对象的生命周期委托给spring。i、 e.您不需要手动创建
对象并调用其ClassA
方法start
注释用于通知spring您想要创建一个类的对象,该类不是spring的@Bean
自动扫描机制的一部分
- 为了将类对象管理委托给spring,应该使用
或它的其他变体(如@Component
、@Controller
等)对类进行注释,或者您应该告诉spring如何使用@Service
注释创建该类的对象@Bean
@Component
和@Bean
,我将把类A标记为Component,并用@Bean
注入变量
@Component
public class ClassA()
{
/*
* Notice this autowired annotation. It tells spring to insert Variable object.
* What you were trying to do with getNeededVar() is done using Autowired annotation
*/
@Autowired
private Variable neededVar;
}
现在告诉spring如何创建变量的对象,因为它没有标记为@Component
@SpringBootApplication
public class Application
{
public static void main( String[] args ) {
SpringApplication.run( Application.class, args );
}
// This is how you register non spring components to spring context.
// so that you can autowire them wherever needed
@Bean
public Variable variable() {
return new Variable();
}
}
您的rest控制器代码保持原样。
由于变量
是通过SpringApplication
类中的@Bean
注册到spring的,所以您实际上不需要ClassA
。
您可以删除它。
@RestController
public class Controller
{
@Autowired
private Variable neededVar;
@RequestMapping( "/temp" )
public string getVar()
{
return neededVar.toString();
}
}
嗨,伙计,谢谢你的回复。我已经把我的代码剥了回去,只显示了必要的(或者我认为是必要的)。我的ClassA实际上做了相当多的工作,是应用程序的“后端”,所以我肯定需要实例化一个,并从中获取needVar。
@Component
public class ClassA()
{
/*
* Notice this autowired annotation. It tells spring to insert Variable object.
* What you were trying to do with getNeededVar() is done using Autowired annotation
*/
@Autowired
private Variable neededVar;
}
@SpringBootApplication
public class Application
{
public static void main( String[] args ) {
SpringApplication.run( Application.class, args );
}
// This is how you register non spring components to spring context.
// so that you can autowire them wherever needed
@Bean
public Variable variable() {
return new Variable();
}
}
@RestController
public class Controller
{
@Autowired
private Variable neededVar;
@RequestMapping( "/temp" )
public string getVar()
{
return neededVar.toString();
}
}