题说明

最近看到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. CF733F Drivers Dissatisfaction【链剖】【最小生成树应用】

    F. Drivers Dissatisfaction time limit per test 4 seconds memory limit per test 256 megabytes input s ...

  2. * -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[0]’

    错误描述: * -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object fr ...

  3. ES6 js中const,var,let区别 今天第一次遇到const定义的变量

    今天第一次遇到const定义的变量,查阅了相关资料整理了这篇文章.主要内容是:js中三种定义变量的方式const, var, let的区别. 1.const定义的变量不可以修改,而且必须初始化. 1 ...

  4. windows命令行下杀死进程的方法

    xp和win7下有两个好东东tasklist和tskill.tasklist能列出所有的进程,和相应的信息.tskill能查杀进程,语法很简单:tskill程序名!或者是tskill 进程id 例如: ...

  5. 详细解读Android中的搜索框(三)—— SearchView

    本篇讲的是如何用searchView实现搜索框,其实原理和之前的没啥差别,也算是个复习吧. 一.Manifest.xml 这里我用一个activity进行信息的输入和展示,配置方式还是老样子,写一个输 ...

  6. 手把手教你用CAB发布OCX的简单办法

    CAB是一种文件压缩格式,把OCX文件(ActiveX插件)压缩成CAB文件是为了发布它,这种发布方式给人感觉“浏览器会自动安装该插件”,很多朋友钟情于此.目前流行很多压缩工具,但WINRAR这类工具 ...

  7. everything结果出现文件找不到

    点击“工具”——“选项”——“索引”——“强制重建”——“确定”, 然后重启everything即可.

  8. 阿里云k8s应用最新日志采集不到的问题

    问题描述: 阿里云k8s应用日志之前一直都是可以正常的采集, 先出现一问题, 通过kibana 和阿里云的日志服务都没法展示最新的k8s应用的日志, 部分应用的最新日志有被采集到,但大部分应用日志没有 ...

  9. iOS蓝色和黄色文件夹新建方式区别(区别之前)

    关于这个问题,好像xcode9之前还是多少来着,创建方式是这样: 1.New Group创建的黄色文件夹是“假”文件夹,也就是说 show in finder 是看不到的 解释:这个文件夹并不是真正的 ...

  10. 如何将Ubuntu Server 12.04 升级到 Ubuntu Server 14.04 LTS

    升级Ubuntu 12.04到Ubuntu 14.04方法如下: 步骤一:在终端中运行下面的命令,它将安装所有的升级包.$ sudo apt-get update && sudo ap ...