您的位置:首页 > 运维架构 > Tomcat

启动tomcat的同时,加载类的方法:采用Spring中的ApplicationContextAware接口

2018-03-19 14:02 411 查看
启动tomcat容器,加载web.xml,建立整个容器(Servlet容器,这里是tomcat吧)的上下文,ServletContext,这时web.xml有个监听器,就是ContextLoaderListener,监听到这个事件,就会去扫描spring配置文件,默认是applicationContext.xml文件(classpath路径下,idea是Resource下),如果自定义,就应该如web.xml中的context-param标签那般配置,扫描这个指定的Spring配置文件,就会将文件中相应的bean加载,其中实现了ApplicationContextAware的bean类会去执行setApplicationContext()方法,将上下文自动初始化。 ContextLoaderListener是用来启动Spring容器,加载Spring上下文的,默认下,会将classpath下的applicationContext.xml文件作为Spring的配置文件,当然,你也可以像web.xml中context-param标签一样,指定路径,不过注意,这里的param-name这一行是不能变得,这是个指定属性值,说明上下文(context)配置(config)文件所在地方(Location)。(注:这一段文字是我在网上百度,觉得说的对,粘贴过来的)
看一下代码吧,红色部分比较重要
java代码:
package com.daoben.robot.controller.web;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
 * @author zhaoxl
 * @date 创建时间:2018年3月19日 上午11:03:07
 * @version 1.0
 * @parameter
 * @describe 启动tomcat的同时加载这个类,就是维持与机器人的长连接
 * @return
 */
@Component
public class SocketMain implements ApplicationContextAware {
private volatile static Thread robotThread; // 实时监控线程
private Logger log = Logger.getLogger(this.getClass());
static int flagStart = 0;
//创建socket
Socket sock;
@Override
public void setApplicationContext(ApplicationContext app) throws BeansException {
log.info("加载程序入口");

if (flagStart == 0) {
//连接机器人
            start();
flagStart = 1;// 防止再次启动
}
 
}
//连接机器人
public void start() {

robotThread = new Thread(new Runnable() {

@Override
public void run() {
while (true) {
sock = null;
try {

InetAddress addr;
// 连接到机器人192.168.0.198服务器的2001端口
// boocaslam:("192.168.0.102", 6789)
// 注册信息: "message_type": "register_client", "client_type":
// 0,
// "mac_address": "2C:94:64:00:F2:1A"
sock = new Socket("192.168.0.198", 2001);
// 获取机器人地址
addr = sock.getInetAddress();
System.out.println("连接到" + addr);
} catch (IOException e) {
System.out.println("无法连接");
System.out.println(e);
} finally {
try {
// 关闭资源
if (sock != null) {
sock.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
});
if (robotThread.isAlive() == false) {
robotThread.setDaemon(true);//
robotThread.start();//
robotThread.setPriority(5);// 优先级高
}
}

}

现在看配置文件:
1.web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>ZNJQR</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<servlet>
<servlet-name>ZNJQR</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ZNJQR</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>

<context-param>
<param-name>webAppRootKey</param-name>
<param-value>WebSGXC_Manage.root</param-value>
</context-param>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:log4j.properties</param-value>
</context-param>
<!-- add by zhaoxl 20170110 start-->
<context-param>  
    <param-name>spring.profiles.active</param-name>  
    <param-value>dev</param-value>  
</context-param>  
<context-param>  
    <param-name>spring.profiles.default</param-name>  
    <param-value>dev</param-value>  
</context-param>  
<context-param>  
    <param-name>spring.liveBeansView.mbeanDomain</param-name>  
    <param-value>dev</param-value>  
</context-param> 
<!-- add by zhaoxl 20170110 end-->
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>

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

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

<filter>
<filter-name>EncodingFilter</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>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<session-config>
<session-timeout>-1</session-timeout>
</session-config>

</web-app>
2.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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd      http://www.springframework.org/schema/aop      http://www.springframework.org/schema/aop/spring-aop-3.0.xsd      http://www.springframework.org/schema/tx     http://www.springframework.org/schema/tx/spring-tx-3.1.xsd     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">

<context:component-scan base-package="com.daoben.robot" />
<!-- 启动AOP支持 -->
<!-- <aop:aspectj-autoproxy/> -->

<!-- 引入外部数据源配置信息 -->
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath:application.properties</value>
</property>
</bean>

<!-- 配置数据源 -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>

<!-- 配置Session工厂 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!-- 加载mybatis.cfg.xml文件 -->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<!-- 自动扫描需要定义类别名的包,将包内的JAVA类的类名作为类别名 -->
<property name="typeAliasesPackage" value="com.daoben.robot.model"></property>
</bean>

<!-- 自动扫描所有的Mapper接口与文件 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.daoben.robot.mapper"></property>
</bean>

<!-- 配置事务管理器 -->
<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>

<!-- 支持 @Transactional 标记 -->
<tx:annotation-driven proxy-target-class="false"
transaction-manager="txManager" />

<!-- 定义文件解释器(文件上传) -->    
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">      
    <!-- 设置默认编码 -->    
    <property name="defaultEncoding" value="utf-8"></property>    
    <!-- 上传图片最大大小1M-->     
    <property name="maxUploadSize" value="1048576"></property>      
</bean> 

</beans>
3.springMvc.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context   http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 启动注解,注册服务,如验证框架、全局类型转换器 -->
<mvc:annotation-driven />

<!-- 启动自动扫描 -->
<context:component-scan base-package="com.daoben.robot">
<!-- <context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" /> -->
<context:exclude-filter type="annotation" 
expression="org.springframework.stereotype.Service" />
</context:component-scan>
  <mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean class="com.daoben.robot.common.SGXCBasedInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
<!-- <context:component-scan base-package="com.cy.ssm" /> -->
<!-- 配置视图解析器 -->
<!-- prefix和suffix:查找视图页面的前缀和后缀(前缀[逻辑视图名]后缀), 比如传进来的逻辑视图名为WEB-INF/jsp/hello,则该该jsp视图页面应该存放在“WEB-INF/jsp/hello.jsp”; -->
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/"></property> <!-- 我这里的视图直接放在WebRoot下的 -->
<property name="suffix" value=".jsp"></property>
</bean>

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
         <!-- 请求编码格式 -->  
         <property name="defaultEncoding" value="utf-8"></property>  
         <!-- 上传文件大小(单位:字节) -->  
         <property name="maxUploadSize" value="41943040"></property>  
         <!-- 缓冲区大小(单位:KB) -->  
         <property name="maxInMemorySize" value="10240"></property>  
    </bean>  
    
    

</beans>
4.mybatis-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org/DTD Config 3.0//EN" 
    "http://mybatis.org/dtd/mybatis-3-config.dtd" >
<configuration>
    <settings>

    <setting name="jdbcTypeForNull" value="NULL" />

</settings>

</configuration>
5.application.properties
jdbc.driver=com.mysql.jdbc.Driver
#mysql allowMultiQueries=true
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
jdbc.username=root
jdbc.password=456789
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息