参考:百度安全验证
这里我列举2种方法,其它方法可以自行学习。
1、BeanUtils代码如下:
package com.hmblogs.backend.util;import org.springframework.context.ApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;public class BeanUtils {public static Object getBean(Class clas){HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();ServletContext servletContext = request.getSession().getServletContext();ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(servletContext);return ac.getBean(clas);}
}
2、SpringUtils代码如下:
package com.hmblogs.backend.util;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;@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {SpringUtils.applicationContext = applicationContext;}public static <T> T getBeanByName(String beanName) {if(applicationContext.containsBean(beanName)){return (T) applicationContext.getBean(beanName);}else{return null;}}public static <T> T getBeanByClass(Class<T> className) {T result = (T) applicationContext.getBean(className);return result;}}
3、验证,测试类代码如下:
package com.hmblogs.backend.util;import com.hmblogs.backend.entity.Blog;
import com.hmblogs.backend.service.BlogServiceImpl;
import com.hmblogs.backend.service.StockServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;@Slf4j
//@Component
@RunWith(SpringRunner.class)
@SpringBootTest
public class BeanTest {@Testpublic void testBean() {// 请求参数BlogServiceImpl blogServiceImpl = (BlogServiceImpl) BeanUtils.getBean(BlogServiceImpl.class);Blog blog = new Blog();blog.setBlogTitle("xxxxxxx");blog.setBlogContent("fdsafadsfadsfdasf");blogServiceImpl.addBlog(blog);}@Testpublic void testBean22() {// 请求参数BlogServiceImpl blogServiceImpl = (BlogServiceImpl) SpringUtils.getBeanByClass(BlogServiceImpl.class);Blog blog = new Blog();blog.setBlogTitle("222222222");blog.setBlogContent("22222sasadsdas");blogServiceImpl.addBlog(blog);}
}