Spring Boot或Cloud的普通類如何獲取service實現(xiàn)
我們在便利使用SpringBoot
或SpringCloud
的時候,很多時候會遇到一種場景,想在utils
的工具類中調(diào)用被Spring
托管的service
.那么我們該如何優(yōu)雅的實現(xiàn)呢?
Num1: 使用PostConstruct
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class OrderUtils {
@Autowired
private OrderService orderService;
public static OrderUtils orderUtils;
public void setService(OrderService orderService) {
this.orderService = orderService;
}
/**
* 核心
*/
@PostConstruct
public void init() {
orderUtils = this;
orderUtils.orderService = this.orderService;
}
public static OrderVo getOrder(String orderId) throws Exception{
OrderVo order= orderUtils.orderService.getOrderById(orderId);
return order;
}
}
被@PostConstruct
修飾的方法會在服務器加載Servlet
的時候運行目代,并且只會被服務器執(zhí)行一次。PostConstruct
在構造函數(shù)之后執(zhí)行普气,init()
方法之前執(zhí)行盖灸。因為注解@PostConstruct
的緣故,在類初始化之前會先加載該使用該注解的方法批旺;然后再執(zhí)行類的初始化访递。
注: 構造方法 ——> @Autowired —— > @PostConstruct ——> 靜態(tài)方法 (按此順序加載)
使用此方法實現(xiàn)service
調(diào)用有一個問題,若想對其他service
進行調(diào)用,需將對應的service
手動注入進來.
Num2:使用ApplicationContextAware
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringUtils.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 對應的被管理類有別名時使用
* @param name
* @param <T>
* @return
* @throws BeansException
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) throws BeansException {
return (T) applicationContext.getBean(name);
}
/**
* 在對應的注解內(nèi)未使用別名時 使用
*/
public static <T> T getBean(Class<T> clazz) {
return applicationContext.getBean(clazz);
}
}
此方法直接實現(xiàn)了ApplicationContextAware
接口,調(diào)用Spring
提供的applicationContext
,將所有在Spring
中有注解的類,均可通過getBean
方式獲取到.