题说明

最近看到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. json字符串转换对象的方法1

    为了方便读者了解json的使用,读者直接粘贴下面代码看效果即可: var json1 = {'name':'小李','age':'11','sex':'女'};console.log(json1.na ...

  2. ssdb安装注意事项

    官网的安装教程依赖于autoconf,需要提前安装.

  3. HttpServerProvider实现http服务接口(一)

    啥也不说了,直接上代码,简单的示例. 服务端代码: package dyan.server; import java.io.BufferedReader; import java.io.IOExcep ...

  4. Voltage Translation for Analog to Digital Interface ADC

    Voltage Translation for Analog to Digital Interface 孕龙逻辑分析仪 ZeroPlus Logic Analyzer How to modify an ...

  5. JVM Debugger Memory View for IntelliJ IDEA

    Posted on August 19, 2016 by Andrey Cheptsov Every day we try to find new ways to improve developer ...

  6. bugly中批量隐藏版本

    App项目使用Bugly的内测分发功能进行整包的测试,但日积月累之后,版本就会特别多.而线上同时跑的版本可能不过三个左右,那么多版本会干扰到查看崩溃.选择版本,如何隐藏呢? 右上角,更多 –> ...

  7. Kubernetes部署ELK并使用Filebeat收集容器日志

    本文的试验环境为CentOS 7.3,Kubernetes集群为1.11.2,安装步骤参见kubeadm安装kubernetes V1.11.1 集群 1. 环境准备 Elasticsearch运行时 ...

  8. mysql insert锁机制

    https://blog.csdn.net/zhanghongzheng3213/article/details/53436240

  9. 使用EF操作不同数据库(以SQLite为例)

    最近一直在和数据库作对. 从安卓平台上给了我个SQLite数据库,要求程序能够读取不同的文件.由于字段实在太多,不愿意直接使用原来直接读取datatable的方式来做,手动写映射太痛苦...于是想起来 ...

  10. Centos下Yum安装PHP 5.5、5.6、7.0

    Centos系统自带的php版本很低,如果我们需要使用高版本的php,可以不用编译安装,直接用yum安装会非常省时省力. 1.检查当前安装的PHP包yum list installed | grep ...