从RequestMapping在main中创建的Spring-Boot Access对象

时间:2015-10-07 09:45:34

标签: spring-boot

我使用spring-boot实现REST服务器。在请求映射的函数内部,我必须创建一个重量级的对象,因此对于每次REST调用我都会这样做,这会减慢速度。是否可以在main中创建对象并从函数中进行访问?

@SpringBootApplication
public class MyClass{

    public static void main(String[] args) {
        /* I want to initialize the object here */
        SpringApplication.run(MyClass.class, args);
    }
}

@RestController
public class MyController {

    @RequestMapping("/go/to/user/summary")
    public Users[] getUsers(@RequestParam(value="length", defaultValue="10") int length) {

/* I want to use the object here */
}

2 个答案:

答案 0 :(得分:2)

您可以在MyClass中创建一个bean,然后在MyController中使用该bean。 Spring只会创建一个bean的单个实例,因此您可以避免多次创建它的成本。像这样:

@SpringBootApplication
public class MyClass {

    public static void main(String[] args) {    
        SpringApplication.run(MyClass.class, args);
    }

    @Bean
    public Heavyweight heavyweight() {
        // Initialize and return heavyweight object here 
    }

}

@RestController
public class MyController {

    private final Heavyweight heavyweight;

    @Autowired
    public MyController(Heavyweight heavyweight) {
        this.heavyweight = heavyweight;
    }

    @RequestMapping("/go/to/user/summary")
    public Users[] getUsers(@RequestParam(value="length", defaultValue="10") int length) {
        // Use heavyweight here
        this.heavyweight.foo();

        // ...

        return users;
    }
}

答案 1 :(得分:1)

我认为你可以使用@Service来实现这种方法。服务类是Singleton所以如果你在启动应用程序中创建对象,那么你可以在你的控制器类中使用它。

示例服务:

@Service
public class MyService{
    private MyLargeObject largeObject;

    public MyLargeObject set(MyLargeObject largeObject){
        this.largeObject = largeObject;
    }

    public MyLargeObject get(){
        return largeObject;
    }
}

控制器示例:

@RestController
public class MyController{

    @Inject
    private MyService myService;

    @RequestMapping("/go/to/user/summary")
    public Users[] getUsers(@RequestParam(value="length", defaultValue="10") int length) {

       MyLargeObject o = myService.get();
    }
}

<强> EDIT1:

如果您想直接在服务中初始化您的largeObject您可以使用@PostConstruct注释。例如:

@PostConstruct
public void init() {
    // initialization Your object here
}