繁体   English   中英

Springboot,使用Rest Controller从对象访问字段

[英]Springboot, accessing field from object with Rest Controller

使用Springboot创建API时遇到麻烦,并了解Beans的工作方式。

我有三节课,我已经尽力简化了。

A类

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控制器(以及随后将创建的所有其他控制器)中,那将不胜感激。

谢谢!

  • 春天不能完全按照您期望的方式工作。 您应该将对象的生命周期委托给spring。 即,您无需手动创建ClassA对象并调用其start方法。
  • @Bean批注用于通知spring您要创建不属于spring autoscan机制一部分的类的对象。
  • 为了将类对象管理委派给spring,应该使用@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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM