首页   注册   登录
V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
拉钩
V2EX  ›  Java

SpringWeb 获取 Bean

  •  
  •   jalena · 2017-05-09 22:21:43 +08:00 · 1543 次点击
    这是一个创建于 583 天前的主题,其中的信息可能已经有所发展或是发生改变。

    Spring 4.3.8

    配置: config/applicationContext.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	   xmlns:context="http://www.springframework.org/schema/context"
    	   xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
    	   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
    		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
    		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    
    	<!-- 自动扫描注解,管理 bean -->
    	<context:component-scan base-package="com.pay.service.*,com.pay.dao.*"/>
    	<context:component-scan base-package="com.pay.model.*,com.pay.dto.*"/>
    
    	<!-- 1.1 加载数据库配置文件 -->
    	<context:property-placeholder location="classpath:jdbc.properties"/>
    
    	<!-- 1.2 配置 Druid 数据源 -->
    	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
    		<!-- 配置连接池属性 -->
    		<property name="driverClassName" value="${jdbc.driver}"/>
    		<property name="url" value="${jdbc.url}"/>
    		<property name="username" value="${jdbc.username}"/>
    		<property name="password" value="${jdbc.password}"/>
    
    		<!-- 配置初始化大小、最小、最大 -->
    		<property name="initialSize" value="${initialSize}"/>
    		<property name="minIdle" value="${minIdle}"/>
    		<property name="maxActive" value="${maxActive}"/>
    
    		<!-- 配置获取连接等待超时的时间 -->
    		<property name="maxWait" value="60000"/>
    
    		<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
    		<property name="timeBetweenEvictionRunsMillis" value="60000"/>
    
    		<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
    		<property name="minEvictableIdleTimeMillis" value="300000"/>
    		<property name="validationQuery" value="SELECT 'x'"/>
    		<property name="testWhileIdle" value="true"/>
    		<property name="testOnBorrow" value="false"/>
    		<property name="testOnReturn" value="false"/>
    
    		<!-- 打开 PSCache,并且指定每个连接上 PSCache 的大小 -->
    		<property name="poolPreparedStatements" value="true"/>
    		<property name="maxPoolPreparedStatementPerConnectionSize" value="20"/>
    
    		<!-- 配置监控统计拦截的 filters,去掉后监控界面 sql 无法统计 -->
    		<property name="filters" value="stat"/>
    	</bean>
    
    	<!-- 1.3 Spring 和 MyBatis 整合,配置 sqlSessionFactory -->
    	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    		<!-- 数据库连接池 -->
    		<property name="dataSource" ref="dataSource"/>
    		<!-- 配置 Mybatis 全局配置文件 -->
    		<property name="configLocation" value="classpath:/config/mybatis-config.xml"/>
    		<!-- 自动扫描 mapping.xml 文件 -->
    		<property name="mapperLocations" value="classpath:/mapper/*.xml"/>
    	</bean>
    
    	<!-- 1.4 扫描 Dao 接口,Spring 会自动查找其下的类,注入到 spring 容器中 -->
    	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    		<!-- 扫描包路径,如果需要扫描多个包,中间使用半角逗号分割 -->
    		<property name="basePackage" value="com.pay.dao"/>
    		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    	</bean>
    
    	<!-- 获取实体 bean 工具类 -->
    	<bean id="beanFactoryUtil" class="com.pay.util.BeanFactoryUtil" lazy-init="false" scope="singleton"/>
    
    	<!-- druid 日志 -->
    	<bean id="logFilter" class="com.alibaba.druid.filter.logging.Slf4jLogFilter">
    		<property name="statementExecutableSqlLogEnable" value="true"/>
    	</bean>
    
    	<!-- 事务管理 -->
    	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    		<property name="dataSource" ref="dataSource"/>
    	</bean>
    
    	<!-- 配置事务的注解方式注入,开启对 Class 的动态代理功能 -->
    	<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
    
    </beans>
    

    config/applicationContext-mvc.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	   xmlns:context="http://www.springframework.org/schema/context"
    	   xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
    	   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
    		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
    		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">
    
    	<!-- 自动扫描包,使 SpringMVC 认为包下用了 @controller 注解的类都是控制器 -->
    	<context:component-scan base-package="com.pay.controller">
    		<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    		<context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
    	</context:component-scan>
    
    
    	<!-- 配置 SpringMVC -->
    	<!-- 1.开启 SpringMVC 注解模式 -->
    	<!-- 简化配置: 
    		(1)自动注册 DefaultAnootationHandlerMapping,AnotationMethodHandlerAdapter 
    		(2)提供一些列:数据绑定,数字和日期的 format @NumberFormat, @DateTimeFormat, xml,json 默认读写支持 
    	-->
    	<!-- 扩充了注解驱动,可以将请求参数绑定到控制器参数 -->
    	<mvc:annotation-driven>
    		<mvc:message-converters register-defaults="true">
    			<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
    			<bean class="org.springframework.http.converter.FormHttpMessageConverter"/>
    			<bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter"/>
    			<bean class="org.springframework.http.converter.StringHttpMessageConverter">
    				<constructor-arg index="0" value="utf-8"/>
    				<property name="supportedMediaTypes">
    					<list>
    						<value>text/plain;charset=UTF-8</value>
    					</list>
    				</property>
    			</bean>
    
    			<!-- 配置 Fastjson 支持 -->
    			<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
    				<property name="supportedMediaTypes" value="application/json"/>
    			</bean>
    		</mvc:message-converters>
    	</mvc:annotation-driven>
    
    	<!-- 避免出现乱码 -->
    
    
    	<!-- 2.静态资源默认 servlet 配置
    		(1)加入对静态资源的处理:js,gif,png
    		(2)允许使用"/"做整体映射
    	 -->
    	<mvc:default-servlet-handler />
    	<mvc:resources mapping="/img/" location="resource/images"/>
    	<mvc:resources mapping="/js/" location="resource/javascript"/>
    	<mvc:resources mapping="/css/" location="resource/css"/>
    
    	<!-- 上传(Servlet3.1) -->
    	<bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver" />
    
    	<!-- 3. 定义跳转文件的前后缀-->
    	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    		<!--<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>-->
    		<property name="prefix" value="/WEB-INF/pages/"/>
    		<property name="suffix" value=".jsp"/>
    	</bean>
    	
    	<!-- 拦截器 -->
    	<mvc:interceptors>
    		<mvc:interceptor>
    			<mvc:mapping path="/admin/**"/>
    			<mvc:exclude-mapping path="/admin/logout"/>
    			<bean id="adminInterceptor" class="com.pay.Interceptor.AdminInterceptor"/>
    		</mvc:interceptor>
    	</mvc:interceptors>
    
    </beans>
    

    web.xml

    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    		 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                          http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    		 version="3.1" metadata-complete="true">
    
    	<welcome-file-list>
    		<welcome-file>admin/login</welcome-file>
    	</welcome-file-list>
    
    	<!-- 加载 Spring 容器 -->
    	<listener>
    		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    	</listener>
    	<context-param>
    		<param-name>contextConfigLocation</param-name>
    		<param-value>classpath*:config/applicationContext.xml</param-value>
    	</context-param>
    
    	<!-- 防止 spring 内存溢出监听器 -->
    	<listener>
    		<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    	</listener>
    
    	<!-- 配置 SpringMVC DispatcherServlet -->
    	<servlet>
    		<servlet-name>SpringMVC</servlet-name>
    		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    		<init-param>
    			<param-name>contextConfigLocation</param-name>
    			<param-value>classpath*:config/applicationContext-mvc.xml</param-value>
    		</init-param>
    		<load-on-startup>1</load-on-startup>
    		<async-supported>true</async-supported>
    		<!--<multipart-config>-->
    			<!--<location>/</location>-->
    			<!--<max-file-size>2097152</max-file-size>-->
    			<!--<max-request-size>4194304</max-request-size>-->
    		<!--</multipart-config>-->
    	</servlet>
    	<servlet-mapping>
    		<servlet-name>SpringMVC</servlet-name>
    		<!-- 默认匹配所有的请求 -->
    		<url-pattern>/</url-pattern>
    	</servlet-mapping>
    
    	<!-- 编码过滤器 -->
    	<filter>
    		<filter-name>CharacterEncodingFilter</filter-name>
    		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    		<init-param>
    			<param-name>encoding</param-name>
    			<param-value>utf-8</param-value>
    		</init-param>
    		<init-param>
    			<param-name>forceEncoding</param-name>
    			<param-value>true</param-value>
    		</init-param>
    	</filter>
    	<filter-mapping>
    		<filter-name>CharacterEncodingFilter</filter-name>
    		<url-pattern>/*</url-pattern>
    	</filter-mapping>
    
    	<!-- 加载 log4j 的配置文件 log4j.properties -->
    	<context-param>
    		<param-name>log4jConfigLocation</param-name>
    		<param-value>classpath:log4j.xml</param-value>
    	</context-param>s
    
    	<!-- Session 超时时间 (分钟)-->
    	<session-config>
    		<session-timeout>15</session-timeout>
    	</session-config>
    </web-app>
    

    写了一个 Bean 获取的工具类 com.pay.util.BeanFactoryUtil

    package com.pay.util;
    
    import org.springframework.beans.BeansException;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.ApplicationContextAware;
    import org.springframework.stereotype.Component;
    
    @Component
    public class BeanFactoryUtil implements ApplicationContextAware {
    
    	public BeanFactoryUtil() {
    	}
    
    	// spring 上下文对象
    	private static ApplicationContext applicationContext;
    
    	@Override
    	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    		this.applicationContext = applicationContext;
    	}
    
    	public static Object getBeanByName(String beanName) throws BeansException{
    		return applicationContext.getBean(beanName);
    	}
    
    	public static Object getBeanByClass(Object beanClass) throws BeansException{
    		return applicationContext.getBean(beanClass.getClass());
    	}
    
    	public static <T> T getBeanByNameAndClass(String beanName, Class<T> requiredType) throws BeansException {
    		return applicationContext.getBean(beanName, requiredType);
    	}
    }
    

    使用这个 util 获取 bean。。。直接报

    获取写法:

    	@RequestMapping(value = "/admin/json")
    	@ResponseBody
    	public PaymentInfo json() {
    
    //		PaymentInfo paymentInfo = BeanFactoryUtil.getBeanByNameAndClass("PaymentInfo",PaymentInfo.class);
    		PaymentInfo paymentInfo = (PaymentInfo) BeanFactoryUtil.getBeanByClass(PaymentInfo.class);
    
    		paymentInfo.setBookfees("aaaaaaaa");
    		paymentInfo.setDepartment("asdas");
    		paymentInfo.setDirection("vccccccccc");
    
    		return paymentInfo;
    	}
    
    javax.servlet.ServletException: org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.Class<?>' available
    	at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:146)
    	at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)
    	at org.eclipse.jetty.server.Server.handle(Server.java:564)
    	at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:317)
    	at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:251)
    	at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:279)
    	at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:110)
    	at org.eclipse.jetty.io.ChannelEndPoint$2.run(ChannelEndPoint.java:124)
    	at org.eclipse.jetty.util.thread.Invocable.invokePreferred(Invocable.java:128)
    	at org.eclipse.jetty.util.thread.Invocable$InvocableExecutor.invoke(Invocable.java:222)
    	at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.doProduce(EatWhatYouKill.java:294)
    	at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.run(EatWhatYouKill.java:199)
    	at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:672)
    	at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:590)
    	at java.lang.Thread.run(Thread.java:745)
    
    7 回复  |  直到 2017-05-16 00:00:42 +08:00
        1
    jalena   2017-05-09 23:47:35 +08:00
    已经搞定!!
    包扫描不能用.*
        2
    liangWL   2017-05-10 08:28:57 +08:00
    楼主配置文件写的真好,能不能发一份,谢谢。新人小白,求罩!
        3
    woshixiaohao1982   2017-05-10 14:54:09 +08:00
    @liangWL 建议 springboot 不要再去配置了了
        4
    jalena   2017-05-11 11:37:37 +08:00
    @liangWL 来个邮箱。
        5
    liangWL   2017-05-12 08:47:56 +08:00
    @jalena 邮箱: awl152022@163.com 多谢了
        6
    liangWL   2017-05-12 11:14:39 +08:00
    再次来谢谢楼主,收到了,谢谢你!!!
        7
    tonyli   2017-05-16 00:00:42 +08:00 via iPhone
    大佬,我们可以交个朋^_^
    关于   ·   FAQ   ·   API   ·   我们的愿景   ·   广告投放   ·   感谢   ·   实用小工具   ·   765 人在线   最高记录 4019   ·  
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.1 · 21ms · UTC 20:42 · PVG 04:42 · LAX 12:42 · JFK 15:42
    ♥ Do have faith in what you're doing.
    沪ICP备16043287号-1