今天来记录一些一定会用到但总忘记怎么写的代码
获取request
public static HttpServletRequest getHttpServletRequest() {
HttpServletRequest request = null;
try {
request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
} catch (Exception ignored) {}
return request;
}
获取某个Service
这里说的是不通过@Autowired进行注入
1.创建一个上下文
package com.youyou.sso.test;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
@Component
@Lazy(false)
public class SpringContextHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public static Object getBean(String name) {
return SpringContextHolder.applicationContext.getBean(name);
}
public static <T> T getBean(Class<T> clazz) {
return SpringContextHolder.applicationContext.getBean(clazz);
}
public static String getValue(String key) {
return SpringContextHolder.applicationContext.getEnvironment().getProperty(key);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextHolder.applicationContext = applicationContext;
}
}
2.测试代码,测试成功
/**
* 登录返回token
* @param userName
* @param password
* @return
*/
@ApiOperation(value = "|登录返回token|")
@GetMapping("/loginByUserInfo")
public String login(String userName , String password){
ISsoService bean = SpringContextHolder.getBean(ISsoService.class);
return bean.login(userName , password);
}
获取配置文件中的值
配置文件
test.user.username = 123
test.user.pass=456
test.number.list[0] = 1
test.number.list[1] = 2
test.number.list[2] = 3
test.number.list[3] = 4
配置文件映射类
package com.youyou.sso.test;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
@Data
@Component("testProperty")
@ConfigurationProperties(prefix = "test")
public class TestProperty {
private ListProperty number = new ListProperty();
private UserProperty user = new UserProperty();
@Data
public static class ListProperty {
private List<String> list = new ArrayList<>();
}
@Data
public static class UserProperty {
private String username;
private String pass;
}
}
/**
* 登录返回token
* @param userName
* @param password
* @return
*/
@ApiOperation(value = "|登录返回token|")
@GetMapping("/loginByUserInfo")
public String login(String userName , String password){
return testProperty.getNumber().toString();
}