当前位置: 首页 > 面试题库 >

Spring Boot RedisTemplate自动装配失败

申颖逸
2023-03-14
问题内容

我试图将spring boot + redis集成到我的应用程序中。

pom.xml中的相关设置如下所示,

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>

应用主要如下

@SpringBootApplication
@EnableTransactionManagement
@ImportResource({"classpath*:applicationContext.xml"})
public class ExamsCenterApplication {

    public static void main(String[] args) {
        SpringApplication.run(ExamsCenterApplication.class, args);
    }
}

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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:util="http://www.springframework.org/schema/util"
    xmlns:mybatis="http://mybatis.org/schema/mybatis-spring" xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc
           http://www.springframework.org/schema/mvc/spring-mvc.xsd
           http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd
           http://www.springframework.org/schema/tx
           http://www.springframework.org/schema/tx/spring-tx.xsd
           http://www.springframework.org/schema/util
           http://www.springframework.org/schema/util/spring-util.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop.xsd
           http://mybatis.org/schema/mybatis-spring
           http://mybatis.org/schema/mybatis-spring.xsd">

<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
    <property name="securityManager" ref="securityManager" />
    <property name="loginUrl" value="/login.jsp" />
    <property name="successUrl" value="/index.jsp" />
    <property name="unauthorizedUrl" value="/unauthorized.jsp" />
    <property name="filters">
        <util:map>
            <entry key="authc">
                <bean
                    class="org.apache.shiro.web.filter.authc.PassThruAuthenticationFilter" />
            </entry>
        </util:map>
    </property>
    <property name="filterChainDefinitions">
        <value>
            /marktask/list/ = authc, perms[scoretask:view]
            /marktask/view/ = authc, perms[scoretask:view]

            /** = anon
        </value>
    </property>
</bean>

<bean id="examCenter" class="org.apache.tomcat.jdbc.pool.DataSource"
    destroy-method="close">
    <property name="poolProperties">
        <bean class="org.apache.tomcat.jdbc.pool.PoolProperties">
            <property name="url"
                value="jdbc:mysql://192.168.100.21:13306/ustudy?characterEncoding=UTF-8&amp;serverTimezone=UTC" />
            <property name="driverClassName" value="com.mysql.jdbc.Driver" />
            <property name="username" value="root" />
            <property name="password" value="mysql" />
            <property name="testWhileIdle" value="true" />
            <property name="testOnBorrow" value="true" />
            <property name="validationInterval" value="30000" />
            <property name="testOnReturn" value="false" />
            <property name="validationQuery" value="/* ping */" />
            <property name="timeBetweenEvictionRunsMillis" value="30000" />
            <property name="maxActive" value="100" />
            <property name="initialSize" value="10" />
            <property name="maxWait" value="10000" />
            <!-- <property name="removeAbandonedTimeout" value="60"/> <property name="minEvictableIdleTimeMillis" 
                value="30000"/> <property name="minIdle" value="10"/> <property name="logAbandoned" 
                value="true"/> <property name="removeAbandoned" value="true"/> <property 
                name="jdbcInterceptors" value="org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer"/> -->
        </bean>
    </property>
</bean>

<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
    <!-- Single realm app. If you have multiple realms, use the 'realms' property 
        instead. -->
    <property name="realm" ref="authRealm" />
    <!-- By default the servlet container sessions will be used. Uncomment 
        this line to use shiro's native sessions (see the JavaDoc for more): -->
    <!-- <property name="sessionMode" value="native"/> -->
</bean>
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />

<!-- Define the Shiro Realm implementation you want to use to connect to 
    your back-end -->
<!-- security datasource: -->
<bean id="authRealm" class="org.apache.shiro.realm.jdbc.JdbcRealm">
    <property name="dataSource" ref="examCenter" />
    <property name="permissionsLookupEnabled" value="true" />
    <property name="authenticationQuery"
        value="select passwd from ustudy.teacher where teacid = ?" />
    <property name="userRolesQuery"
        value="select role_name from ustudy.teacherroles where teac_id = ?" />
    <property name="permissionsQuery"
        value="select perm from ustudy.perms where role_name = ?" />
</bean>
<bean
    class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
    depends-on="lifecycleBeanPostProcessor" />
<bean
    class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
    <property name="securityManager" ref="securityManager" />
</bean>

<!-- Secure Spring remoting: Ensure any Spring Remoting method invocations 
    can be associated with a Subject for security checks. -->
<bean id="secureRemoteInvocationExecutor"
    class="org.apache.shiro.spring.remoting.SecureRemoteInvocationExecutor">
    <property name="securityManager" ref="securityManager" />
</bean>

<!-- Noted: Two methods for enabling spring transaction managent with jdbc. 
    Above is XML based configuration. Declaring with @Transactional in java source 
    code is also very flexible. -->
<tx:annotation-driven transaction-manager="txManager" />
<bean id="txManager"
    class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="examCenter" />
</bean>

<!-- sql session factory for mybatis -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="examCenter" />
    <property name="mapperLocations" value="classpath:com/ustudy/exam/mapping/*.xml"></property>  
</bean>

<!-- scan for mappers and make them autowired -->
<mybatis:scan base-package="com.ustudy.exam.mapper" />
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.ustudy.exam.dao" />
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>

<!-- spring data redis related configurations -->
<bean id="jedisConnectionFactory"
    class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
    p:use-pool="true" p:database="0" p:host-name="192.168.100.21" p:port="6379"
    p:timeout="100" />

<!-- redis template definition -->
<bean id="stringSerializer"
    class="org.springframework.data.redis.serializer.StringRedisSerializer" />
<bean id="jdkSerializer"
    class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
<bean id="jsonSerializer"
    class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" />
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
    p:connection-factory-ref="jedisConnectionFactory">
    <property name="keySerializer" ref="stringSerializer" />
    <property name="valueSerializer" ref="jsonSerializer" />
</bean>

<context:annotation-config />
<bean
    class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration" />

我的服务代码如下

@Service
public class MetaInfo {

    private static final Logger logger = LogManager.getLogger(MetaInfo.class);

    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate<String, Object> redisT;

    /*
     * only need basic information about this question, assign mode. not sure whether other info needed.
     */
    public QuesMeta getMetaTaskInfo(String quesid) {
        logger.debug("getMetaTaskInfo() hitted");
        QuesMeta qm = new QuesMeta("redistest", "auto");
        redisT.opsForValue().set("001", qm);

        if (redisT == null) {
            logger.debug("getMetaTaskInfo(), redisTemplate is not initialized.");
            return null;
        }
        redisT.opsForValue().set("redistest", "hello");
        logger.debug("getMetaTaskInfo(), stored data in redis");
        return null;
    }

然后运行程序并得到以下异常,

java.lang.NullPointerException: null
at com.ustudy.cache.MetaInfo.getMetaTaskInfo(MetaInfo.java:42) ~[classes/:0.0.1-SNAPSHOT]
at com.ustudy.exam.controller.MarkTaskController.getMarkTask(MarkTaskController.java:37) ~[classes/:0.0.1-SNAPSHOT]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_151]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_151]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_151]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_151]

似乎下面的代码出错了。

@Autowired
private RedisTemplate<String, String> redisT;

redisT为null,未按预期初始化。

我应该如何解决此问题?

非常感谢。


问题答案:

我的控制器代码确实犯了一个错误。我的原始控制器代码如下

@RestController
@RequestMapping(value="/exam/")
public class MarkTaskController {

    private static final Logger logger = LogManager.getLogger(MarkTaskController.class);

    @Autowired
    private MarkTaskService stS;


    @RequestMapping(value = "/marktask/list/", method = RequestMethod.GET)
    public List<MarkTaskBrife> getMarkTask(HttpServletResponse resp) {
        logger.debug("getMarkTask(), start to retrieving all examination result.");

        new MetaInfo().getMetaTaskInfo(null);
        return null;

代码“ new MetaInfo()”不正确。还应按以下方式自动接线,

@Autowired
    private MetaInfo mi;

    @RequestMapping(value = "/marktask/list/", method = RequestMethod.GET)
    public List<MarkTaskBrife> getMarkTask(HttpServletResponse resp) {
        logger.debug("getMarkTask(), start to retrieving all examination result.");

        mi.getMetaTaskInfo(null);
        return null;

然后一切正常。

非常感谢@Chacko在此问题上的帮助。



 类似资料:
  • 问题内容: 我的文凭项目有一个大问题,如果你们能帮助我,我将非常高兴!我做了一个Maven多模块项目,有3个“核心项目” :(父母) :包含所有的实体和接口域模型是由需要 和对 :将GUI和Hessian关联起来 :这里是我的仓库,我到数据库连接和接口的实现 和具有在Maven作为依赖。 现在,每次尝试在Tomcat上启动服务器时,都会出现以下错误: 模型库: 卡萨: MeinRemoteDien

  • 最近,我遇到了一种情况,即基于Spring的应用程序在访问类(A)中的自动连接字段时抛出“NullPointerApplication”。被自动连接的豆子也用于其他类(B和C)。这些类(B和C)在访问该bean时工作正常。 当我重新启动应用程序时,一切正常。如前所述,如果bean自动连接失败,则类bean创建应失败,应用程序不应启动。相反,应用程序运行良好(A类除外),并且找不到“无法自动连线”异

  • 使用springboot集成mybatis时,在配置文件中配置了扫描xml文件路径, 但是运行的时候告诉我找不到对应的mapper这个bean,这貌似没有给我进行自动装配,如果所示: yml配置如下 这个是mapper对应路径,在mapper接口上加上@Mapper注解或者启动类MapperScan后就可以正常使用,但是想知道为什么,在yml中不是配置的扫描路径没有生效,不会给我自动去扫描 尝试着

  • 主要内容:Spring 自动装配,自动装配规则,示例我们把 Spring 在 Bean 与 Bean 之间建立依赖关系的行为称为“装配”。 Spring 的 IOC 容器虽然功能强大,但它本身不过只是一个空壳而已,它自己并不能独自完成装配工作。需要我们主动将 Bean 放进去,并告诉它 Bean 和 Bean 之间的依赖关系,它才能按照我们的要求完成装配工作。 在前面的学习中,我们都是在 XML 配置中通过 <constructor-arg>和 <

  • 问题内容: 我想在servlet中使用spring自动装配,所以这是我的代码: 而用注释 和我的applicationContext.xml: 有时自动装配有效,有时却无效(对spring bean systemPropertyDao的引用为null),有人可以告诉我是否缺少什么吗? 问题答案: 我在以下链接中遵循了该解决方案,并且工作正常: 从JBoss中的servlet访问Spring Bea

  • 主要内容:1.分析,2.样例讲解1,3.样例讲解2,4.总结1.分析 先看@SpringBootApplication @SpringBootConfiguration:标记当前类为配置类 @EnableAutoConfiguration:开启自动配置 @ComponentScan:扫描主类所在的同级包以及下级包里的Bean @EnableAutoConfiguration: @Import(AutoConfigurationImportSelector.