题说明

最近看到Spring事务,在学习过程中遇到一个很苦恼问题

搭建好Spring的启动环境后出现了一点小问题

在启动时候却出现[java.lang.NullPointerException]

不过因为当时一个小小的疏忽 很low的问题 请往下看 ...

工程结构

代码片段

spring.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xmlns:context="http://www.springframework.org/schema/context"
5 xsi:schemaLocation="
6 http://www.springframework.org/schema/beans
7 http://www.springframework.org/schema/beans/spring-beans.xsd
8 http://www.springframework.org/schema/context
9 http://www.springframework.org/schema/context/spring-context.xsd">
10
11 <!-- Spring注解扫描 -->
12 <context:component-scan base-package="com.*" />
13
14 <!-- 1. 数据源对象: C3P0连接池 -->
15 <bean id="dataSource"
16 class="com.mchange.v2.c3p0.ComboPooledDataSource">
17 <property name="driverClass" value="org.h2.Driver"></property>
18 <property name="jdbcUrl"
19 value="jdbc:h2:tcp://192.168.190.1/~/test"></property>
20 <property name="user" value="sa"></property>
21 <property name="password" value="123"></property>
22 </bean>
23
24 <!-- 2. JdbcTemplate工具类实例 -->
25 <bean id="jdbcTemplate"
26 class="org.springframework.jdbc.core.JdbcTemplate">
27 <property name="dataSource" ref="dataSource"></property>
28 </bean>
29
30 <!-- 3.配置事务 -->
31 <bean id="dataSourceTransactionManager"
32 class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
33 <property name="dataSource" ref="dataSource"></property>
34 </bean>
35
36 </beans>

 Test.java

1 public class Test {
2 public static void main(String[] args) {
3 ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext(
4 "spring.xml");
5 ServiceIF service = (ServiceIF) classPathXmlApplicationContext.getBean("serviceImpl");
6 service.add("小王", 23);
7 }
8 }

TransactionUtil.java

 1 @Component("transactionUtil")
2 public class TransactionUtil {
3
4 /**
5 * 初始化数据源
6 */
7 @Autowired
8 private DataSourceTransactionManager dataSourceTransactionManager;
9
10 /**
11 * 开启事务
12 *
13 * @return
14 */
15 public TransactionStatus begin() {
16 TransactionStatus transaction = dataSourceTransactionManager.getTransaction(new DefaultTransactionDefinition());
17 System.out.println(" 开启事务成功 ");
18 return transaction;
19 }
20
21 /**
22 * 提交事物
23 *
24 * @param transaction
25 */
26 public void commit(TransactionStatus transaction) {
27 dataSourceTransactionManager.commit(transaction);
28 System.out.println(" 事物提交成功 ");
29 }
30
31 /**
32 * 回滚事务
33 *
34 * @param transaction
35 */
36 public void rollback(TransactionStatus transaction) {
37 dataSourceTransactionManager.rollback(transaction);
38 System.err.println(" 事物进行回滚 ");
39 }
40 }

ServiceImpl.java

 1 @Service("serviceImpl")
2 public class ServiceImpl implements ServiceIF {
3
4 @Autowired
5 TransactionUtil transactionUtil;
6
7 private TransactionStatus transactionStatus = null;
8
9 @Override
10 public void add(String name, Integer age) {
11 transactionStatus = transactionUtil.begin();
12 try {
13 new DaoImpl().add(name, age);
14 transactionUtil.commit(transactionStatus);
15 } catch (Exception e) {
16 System.err.println("ERROR >>> 执行出现异常 即将进行回滚操作");
17 transactionUtil.rollback(transactionStatus);
18 }
19 }
20 }

DaoImpl.java

 1 public class DaoImpl implements DaoIF{
2
3 /**
4 * 注入jdbc模板类
5 */
6 @Autowired
7 private JdbcTemplate jdbcTemplate;
8
9 /**
10 * 第一条插入语句
11 */
12 private final String SQL_INSERT_01 = "insert into user values (?,?)";
13
14 /**
15 * 添加sql执行
16 *
17 * @param name
18 * @param age
19 */
20 public void add(String name, Integer age) {
21 jdbcTemplate.update(SQL_INSERT_01, name, age);
22 }
23 }

运行结果

问题分析


解决思路

我在想 为什么会没有注入进来呢 我明明加了@Autowired注解

后来猜到可能是Spring.xml配置的问题

看完也没有问题 我就从Java Source一步一步看 发现....

我靠 我就猜测是不是如果用「new Object()」的方式创建实例后 其class中的Bean的注解会失效呢?

然后我尝试在ServiceImpl.java中以注解的方式把DaoIF的实例注入到ServiceImpl,

并在DaoImpl.java的类上面添加@Repository,

把ServiceImpl.java中new DaoImpl()替换成注入的daoImpl。

改修代码

ServiceImpl.java修改后

DaoImpl.java修改后


改修后调试


其实我懂得也不太多 Spring注入的流程那

首先他会把项目中target -> classes 目录下的「.class」文件进行解析

通过Spring.xml中的「context:component-scan」进行注解扫描

如果这个路径下的「.class」文件的类上面是否存在@Component声明的注解

如果被此类注解修饰,Spring会把所有被注解修饰的bean进行实例化操作  供给@Autowired进行注入

(在spring注解的源码中@Service和@Repository等等都继承了@Component注解)

  结论 

在使用Spring的Bean容器时 千万要确保

                配置的注解扫描路径正确

                Jar的依赖是否存在

                是否在bean的上面加「@Service @Repository @Component … 」

               要细心 遇到异常不要紧 慢慢分析!!!

https://www.cnblogs.com/cat-/p/10014477.html

@Autowired注入为null问题分析的更多相关文章

  1. struts2的action中@Autowired注入为null的解决方案

    今天遇到类似问题,记录下来以便以后查阅: @Aspect作用于action,致使action中的@Autowired注入为null的解决方案,以下三种任选一种: 1.去掉@Autowired,改用se ...

  2. 关于工具类中@Autowired注入为NULL的问题记录

      记录:在实体类中加入@Component注解和@Autowired注解时Service不能注入成功. @Component //把普通pojo实例化到spring容器中 0 public clas ...

  3. Java 各级注解及@Autowired注入为null解决办法

    1.@controller 控制器 用于标注控制层,相当于struts中的action层. 2.@service 服务层 用于标注服务层,主要用来进行业务的逻辑处理. 3.@repository DA ...

  4. 于工具类中@Autowired注入为NULL的问题记录

      记录:在实体类中加入@Component注解和@Autowired注解时Service不能注入成功. ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 ...

  5. spring@Autowired注入为null的问题,2017年9月14日21点41分记录

    这个小问题纠结了三个小时..发出来留个纪念 这是启动项目的时候 这是请求控制器的时候   图1注入的时候是null,图2请求控制器的时候是有的,这是因为图1debug的地方是构造器..autowire ...

  6. Struts2学习:Action使用@Autowired注入为null的解决方案

    1.pom.xml引入struts2-spring-plugin <dependency> <groupId>org.apache.struts</groupId> ...

  7. Spring @Autowired 注入为 null

    原因 配置缺失,比如为开启注解扫描驱动.注入组件为注册: 使用 new 关键字创建的对象不受spring容器管理,无法注入: 注入静态变量, 静态变量/类变量不是对象的属性,而是一个类的属性,spri ...

  8. 欲哭无泪的@Autowired注入对象为NULL

    欲哭无泪啊...一下午的时间就这么被浪费了...一个基于spring mvc和spring data jpa的小项目,当我写完一个controller的测试用例后,一运行却报空指针,跟了下是一个dao ...

  9. Spring @Autowired注解在非Controller中注入为null

    问题描述 今天在写一个工具类,里面用了@Autowired注入了StringRedisTemplate以及RedisTemplate时,在template.opsForValue().set(key, ...

随机推荐

  1. Unity3D引擎中特殊的文件夹

    Editor Editor文件夹可以在根目录下,可以在子目录里,只要名是Editor就可以./xxx/xxx/Editor  和 /Editor 是一样的,多少个叫Editor的文件夹都可以.Edit ...

  2. 添加 vip

    两台机器:172.16.91.101 172.16.91.107 在91.101上增加虚拟ip,92网段的 ifconfig eth0:1 172.16.92.2 netmask 255.255.25 ...

  3. C#轻量级日志监控器EasyLogMonitor

    一.课程介绍 本次分享课程属于<C#高级编程实战技能开发宝典课程系列>中的一部分,阿笨后续会计划将实际项目中的一些比较实用的关于C#高级编程的技巧分享出来给大家进行学习,不断的收集.整理和 ...

  4. Java int转string 长度不足左补0

    最近项目中用到这个需求,我试了两个方法都可以实现 方法一:(推荐) String s=String.format("%010d", 123)//123为int类型,0代表前面要补的 ...

  5. A very simple C++ module to encrypt/decrypt strings based on B64 and Vigenere ciper.

    A very simple C++ module to encrypt/decrypt strings based on B64 and Vigenere ciper. https://github. ...

  6. Node.js Cheerio parser breaks UTF-8 encoding

    From: https://stackoverflow.com/questions/31574127/node-js-cheerio-parser-breaks-utf-8-encoding [问题] ...

  7. MAC常用软件推荐

    SQL建模 http://dbwrench.com/download/install/mac_install.shtml 参考https://github.com/helantao/macOS/blo ...

  8. shell while内获取外部变量内容

    一.问题 问题很简单,看下面一段tmp.sh代码: #!/bin/sh x="this is the initial value of x" cat /tmp/tmp | whil ...

  9. maven本地库与私服比对,查找缺失jar包

    项目中遇到的一个问题,因为要切换开发环境(新环境不能联网,且私服上的jar包信息不全),需要将本地仓库(项目使用本地仓库能够正常编译)中有而私服上没有的jar包整理出来(名称.版本号等),提供给第三方 ...

  10. 11g新特性-SQL Plan Management

    在11g之前版本,提供了stored outlines(sql概要)特性来保存sql的执行计划. 在11g中,引入了一个新的特性sql计划管理(sql plan management)特性来保存sql ...