spring 构造函数注入后怎么用
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring 构造函数注入后怎么用相关的知识,希望对你有一定的参考价值。
spring的对象bean被成功注入后,可以通过以下的方式取得注入bean:
1、(多在struts框架中)继承BaseDispatchAction
import com.mas.wawacommunity.wap.service.UserManager;public class BaseDispatchAction extends DispatchAction
/**
* web应用上下文环境变量
*/
protected WebApplicationContext ctx;
protected UserManager userMgr;
/**
* 获得注册Bean
* @param beanName String 注册Bean的名称
* @return
*/
protected final Object getBean(String beanName)
return ctx.getBean(beanName);
protected ActionForward unspecified(ActionMapping mapping, ActionForm form,
javax.servlet.http.HttpServletRequest request,
javax.servlet.http.HttpServletResponse response)
return mapping.findForward("index");
public void setServlet(ActionServlet servlet)
this.servlet = servlet;
this.ctx = WebApplicationContextUtils.getWebApplicationContext(servlet.getServletContext());
this.userMgr = (UserManager) getBean("userManager");
2、实现BeanFactoryAware接口,一定要在spring.xml中加上:
当对serviceLocator实例时就自动设置BeanFactory,以便后来可直接用beanFactory。
private static BeanFactory beanFactory = null;
private static ServiceLocator servlocator = null;
public void setBeanFactory(BeanFactory factory) throws BeansException
this.beanFactory = factory;
public BeanFactory getBeanFactory()
return beanFactory;
public static ServiceLocator getInstance()
if (servlocator == null)
servlocator = (ServiceLocator) beanFactory.getBean("serviceLocator");
return servlocator;
/**
* 根据提供的bean名称得到相应的服务类
* @param servName bean名称
*/
public static Object getService(String servName)
return beanFactory.getBean(servName);
/**
* 根据提供的bean名称得到对应于指定类型的服务类
* @param servName bean名称
* @param clazz 返回的bean类型,若类型不匹配,将抛出异常
*/
public static Object getService(String servName, Class clazz)
return beanFactory.getBean(servName, clazz);
action调用:
public class UserAction extends BaseAction implements Action,ModelDrivenprivate Users user = new Users();
protected ServiceLocator service = ServiceLocator.getInstance();
UserService userService = (UserService)service.getService("userService");
public String execute() throws Exception
return SUCCESS;
public Object getModel()
return user;
public String getAllUser()
HttpServletRequest request = ServletActionContext.getRequest();
List ls=userService.LoadAllObject( Users.class );
request.setAttribute("user",ls);
this.setUrl("/yonghu.jsp");
return SUCCESS;
3、实现ApplicationContextAware 接口,一定要在spring.xml中加上:
当对SpringContextUtil 实例时就自动设置applicationContext,以便后来可直接用applicationContext
private static ApplicationContext applicationContext; //Spring应用上下文环境
/**
* 实现ApplicationContextAware接口的回调方法,设置上下文环境
* @param applicationContext
* @throws BeansException
*/
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
SpringContextUtil.applicationContext = applicationContext;
/**
* @return ApplicationContext
*/
public static ApplicationContext getApplicationContext()
return applicationContext;
/**
* 获取对象
* @param name
* @return Object 一个以所给名字注册的bean的实例
* @throws BeansException
*/
public static Object getBean(String name) throws BeansException
return applicationContext.getBean(name);
/**
* 获取类型为requiredType的对象
* 如果bean不能被类型转换,相应的异常将会被抛出(BeanNotOfRequiredTypeException)
* @param name bean注册名
* @param requiredType 返回对象类型
* @return Object 返回requiredType类型对象
* @throws BeansException
*/
public static Object getBean(String name, Class requiredType) throws BeansException
return applicationContext.getBean(name, requiredType);
/**
* 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true
* @param name
* @return boolean
*/
public static boolean containsBean(String name)
return applicationContext.containsBean(name);
/**
* 判断以给定名字注册的bean定义是一个singleton还是一个prototype。
* 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)
* @param name
* @return boolean
* @throws NoSuchBeanDefinitionException
*/
public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException
return applicationContext.isSingleton(name);
/**
* @param name
* @return Class 注册对象的类型
* @throws NoSuchBeanDefinitionException
*/
public static Class getType(String name) throws NoSuchBeanDefinitionException
return applicationContext.getType(name);
/**
* 如果给定的bean名字在bean定义中有别名,则返回这些别名
* @param name
* @return
* @throws NoSuchBeanDefinitionException
*/
public static String[] getAliases(String name) throws NoSuchBeanDefinitionException
return applicationContext.getAliases(name);
action调用:
package com.anymusic.oa.webwork;import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import com.anymusic.oa.commons.service.ServiceLocator;
import com.anymusic.oa.hibernate.pojo.Role;
import com.anymusic.oa.hibernate.pojo.Users;
import com.anymusic.oa.spring.IUserService;
import com.opensymphony.webwork.ServletActionContext;
import com.opensymphony.xwork.Action;
import com.opensymphony.xwork.ActionContext;
import com.opensymphony.xwork.ModelDriven;
public class UserAction extends BaseAction implements Action,ModelDriven
private Users user = new Users();
//不用再加载springContext.xml文件,因为在web.xml中配置了,在程序中启动是就有了.
UserService userService = (UserService) SpringContextUtil.getBean("userService");
public String execute() throws Exception
return SUCCESS;
public Object getModel()
return user;
public String getAllUser()
HttpServletRequest request = ServletActionContext.getRequest();
List ls=userService.LoadAllObject( Users.class );
request.setAttribute("user",ls);
this.setUrl("/yonghu.jsp");
return SUCCESS;
4、通过servlet 或listener设置spring的ApplicationContext,以便后来引用.
注意分别extends ContextLoaderListener和ContextLoaderServlet .然后就可用SpringContext来getBean.
覆盖原来在web.xml中配置的listener或servlet.
private static ApplicationContext applicationContext; //Spring应用上下文环境
*/
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
SpringContextUtil.applicationContext = applicationContext;
/**
* @return ApplicationContext
*/
public static ApplicationContext getApplicationContext()
return applicationContext;
*/
public static Object getBean(String name) throws BeansException
return applicationContext.getBean(name);
public class SpringContextLoaderListener extends ContextLoaderListener //
public void contextInitialized(ServletContextEvent event)
super.contextInitialized(event);
SpringContext.setApplicationContext(
WebApplicationContextUtils.getWebApplicationContext(event.getServletContext())
);
public class SpringContextLoaderServlet extends ContextLoaderServlet
private ContextLoader contextLoader;
public void init() throws ServletException
this.contextLoader = createContextLoader();
SpringContext.setApplicationContext(this.contextLoader.initWebApplicationContext(getServletContext()));
参考技术A private IUserService userService;
类似上面的
不可变构造函数注入 Kotlin 类的正确方法
【中文标题】不可变构造函数注入 Kotlin 类的正确方法【英文标题】:Correct approach for immutable constructor injected Kotlin class 【发布时间】:2016-01-24 08:31:09 【问题描述】:用 Spring + Kotlin 声明不可变构造函数注入类的正确方法是什么?目前我有:
@RestController
public class AuthorizationController
@Inject
lateinit var facebookAuth: FacebookAuthorizationService //Mutable?
@RequestMapping("/authorization")
public fun authorization(@RequestParam(value = "network-type", defaultValue = "Facebook") name: String,
@RequestParam(value = "oauth-token") oauthToken: String,
@RequestParam(value = "oauth-token-secret",
required = false) oauthTokenSecret: String?): Authorization
//TODO: Handle other network types
return facebookAuth.authorization(oauthToken)
我希望 facebookAuth 属性是不可变的。
【问题讨论】:
【参考方案1】:这里对Kotlin的经验不多,但我觉得一定要用
public class AuthorizationController @Inject constructor(private val facebookAuth: FacebookAuthorizationService)
...
【讨论】:
以上是关于spring 构造函数注入后怎么用的主要内容,如果未能解决你的问题,请参考以下文章