参考:百度安全验证
这里我列举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代码如下:文章来源:https://www.toymoban.com/news/detail-849217.html
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;
@Override
public 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、验证,测试类代码如下:文章来源地址https://www.toymoban.com/news/detail-849217.html
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 {
@Test
public void testBean() {
// 请求参数
BlogServiceImpl blogServiceImpl = (BlogServiceImpl) BeanUtils.getBean(BlogServiceImpl.class);
Blog blog = new Blog();
blog.setBlogTitle("xxxxxxx");
blog.setBlogContent("fdsafadsfadsfdasf");
blogServiceImpl.addBlog(blog);
}
@Test
public void testBean22() {
// 请求参数
BlogServiceImpl blogServiceImpl = (BlogServiceImpl) SpringUtils.getBeanByClass(BlogServiceImpl.class);
Blog blog = new Blog();
blog.setBlogTitle("222222222");
blog.setBlogContent("22222sasadsdas");
blogServiceImpl.addBlog(blog);
}
}
到了这里,关于spring获取bean的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!