![](/img/trans.png)
[英]Problems accessing REST endpoints from Springboot application deployed on Tomcat
[英]Springboot, accessing field from object with Rest Controller
使用Springboot创建API时遇到麻烦,并了解Beans的工作方式。
我有三节课,我已经尽力简化了。
public class ClassA()
{
private variable neededVar;
public ClassA()
{
//initialise other variables;
}
public start()
{
/initialise neededVar;
}
@Bean
public variable getNeededVar()
{
return neededVar;
}
}
@SpringBootApplication
public class Application
{
private static ClassA myClass;
public static void main( String[] args )
{
myClass = new ClassA();
ClassA.start();
SpringApplication.run( Application.class, args );
}
}
@RestController
public class Controller
{
@Autowired
private variable neededVar;
@RequestMapping( "/temp" )
public string getVar()
{
return neededVar.toString();
}
}
我的问题是,在控制器中,我没有从创建的ClassA对象myClass中获得neededVar,实际上我不确定自己要得到什么。
我也尝试过以这种方式进行操作,结果相似。
@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 );
}
}
如果有人能指出正确的方向,将我需要的Var从应用程序中的实例化ClassA导入到我的rest控制器(以及随后将创建的所有其他控制器)中,那将不胜感激。
谢谢!
ClassA
对象并调用其start
方法。 @Bean
批注用于通知spring您要创建不属于spring autoscan
机制一部分的类的对象。 @Component
或其他变体(例如@Controller
, @Service
@Controller
等)对类进行注释,或者应告诉spring如何使用@Bean
注释创建该类的对象。 为了展示如何使用@Component
和@Bean
,我将Class A标记为组件,并使用@Bean
注入Variable
。
@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如何为Variable
创建对象,因为它没有标记为@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();
}
}
您的休息控制器代码保持不变。 由于Variable
是通过@Bean
类中的SpringApplication
为spring的,因此您实际上不需要ClassA
。 您可以删除它。
@RestController
public class Controller
{
@Autowired
private Variable neededVar;
@RequestMapping( "/temp" )
public string getVar()
{
return neededVar.toString();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.