如何通过Spring在Controller中添加构造函数

xuy*_*ing 1 java spring

我想初始化三个属性(companyTypescarrierLists,和cabinLevels)为全局变量:

@Controller
@RequestMapping("/backend/basic")
public class TicketRuleController {
    @Autowired
    private CarrierService carrierService;
    @Autowired
    private CabinLevelService cabinLevelService;
    @Autowired
    private CompanyTypeService companyTypeService;
    private List<DTOCompanyType> companyTypes = companyTypeService.loadAllCompanyTypes();
    private List<DTOCarrier> carrierLists = carrierService.loadAllCarriers();
    private List<DTOCabinLevel> cabinLevels = cabinLevelService.loadAllCabinLevel(); 
    ...
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

Pau*_*nis 6

依赖项注入完成后,有几种方法可以执行初始化:您可以在某些方法上使用@PostConstruct批注。例如:

@PostConstruct
public void initialize() {
   //do your stuff
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用Spring的InitializingBean接口。创建一个实现此接口的类。例如:

@Component
public class MySpringBean implements InitializingBean {


    @Override
    public void afterPropertiesSet()
            throws Exception {
       //do your stuff
    }
}
Run Code Online (Sandbox Code Playgroud)