请问各位如何在controller中获取application-context.xml的bean

这是webxml中的配置

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value> 
        classpath:application-context.xml </param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>example</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>example</servlet-name>
        <url-pattern>/api/*</url-pattern>
    </servlet-mapping>

如何通过controller中获取bean,如果使用ClassPathApplicationContext获取会报错,请问该怎么办啊?各位大哥谁能帮一下啊

阅读 3.2k
2 个回答

在controller中获取bean可以使用注解哇:
1.在你的Spring配置中加入 <context:component-scan base-package="cn.lonecloud.xxx" annotation-config="true"/>
2.比如你需要获取userService的一个Bean
使用@Autowired注解

    @Autowired
    protected UserService userService;

3.前提需要在你需要的注解类中加入@service

@Service
public class UserService

即可获取得到

新手上路,请多包涵

写一个springUtils类
在spring的xml里添加这个bean
<bean class="com.xxx.util.SpringUtils"/>

springUtils里继承BeanFactoryPostProcessor类
private static ConfigurableListableBeanFactory beanFactory; // Spring应用上下文环境
添加这个属性(getter和setter不写了)
下面那个方法就是获取bean
public static <T> T getBean(String name) throws BeansException {

    return (T) beanFactory.getBean(name);
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题