当前位置 博文首页 > 程序员石磊:Spring boot enable Lazy Initialization of bean
For example:
DemoController.Java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping
public class DemoController {
DemoController(){
System.out.println("Controller init...");
}
@Autowired
private EmployeeService employeeService;
@RequestMapping("/demo")
public String demo(){
System.out.println("Preparing HTTP request...");
return "This is from demo";
}
}
EmployeeService.Java
import org.springframework.stereotype.Service;
@Service
public class EmployeeService {
public EmployeeService(){
System.out.println("Service Init ...");
}
}
输出:
在第一个请求中,依赖 bean 将被初始化。wget http://localhost:8181/demo
Controller init...
Service Init ...
Preparing HTTP request...
true
value 表示懒加载
spring.main.lazy-initialization=true
true
value 表示懒加载
@SpringBootApplication
public class SpringBootConfig {
public static void main(String[] args) throws Exception {
SpringApplication application = new SpringApplication(SpringBootConfig.class);
application.setLazyInitialization(true);
application.run();
}
}
@Service
@Lazy(value = false) // disable lazy for this bean
public class EmployeeService {
public EmployeeService(){
System.out.println("Service Init ...");
}
}
cs