@autowired注入失败_@Autowired注入值为空怎么办

练习spring时发现Autowired注入值为空

/**
接口
**/
public interface UserService {
    public void save();
}
/**
实现类
**/
package com.zzr.demo.service;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Service("service")
public class UserServiceImpl implements UserService{

    @Override
    public void save() {
        System.out.println("业务逻辑代码");
    }
}

applicationContext.xml

<!--注解扫描开启-->
 	<context:component-scan base-package="com.zzr.demo"/>
   <!-- <bean id="service" class="com.zzr.demo.service.UserServiceImpl"/>-->
    
    <bean id="myXmlAspects" class="com.zzr.demo.aspects.MyXmlAspects"/>

    <aop:config>
        <!--配置切面-->
        <aop:aspect ref="myXmlAspects">
            <!--五种通知类型
            aop:before:前置通知,目标方法执行前,执行增强方法
            aop:after:最终通知,目标方法执行后,无论成功或失败必执行
            aop:after-reterning:后置通知,目标方法执行成功后,执行增强方法
            aop:after-throwing:异常通知,目标方法执行失败后,执行增强方法
            aop:around:环绕通知,目标方法执行前后,都可以进行增强,目标对象的方法需要手动执行-->
            <aop:before method="log" pointcut="execution(public void com.zzr.demo.service.UserServiceImpl.save())"/>
        </aop:aspect>
    </aop:config>

切面类,应该跟这个没关系,但是还是贴出来吧

public class MyXmlAspects {
    //模拟实现日志
    public void log(){
        System.out.println("通知执行");
    }

    public void arroundLog(ProceedingJoinPoint point){
        try {
            System.out.println("目标方法执行前");
            point.proceed();
            System.out.println("目标方法执行后");
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }finally {
            System.out.println("xxx");
        }
    }
}

测试类

public class Test1 {
    public UserService getService(){
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService service = (UserService) ac.getBean("service");
        return service;
    }
    @Test
    public void run1(){
        UserService service = this.getService();
        service.save();
    }


//    @Resource
    @Autowired
//    @Qualifier("service")
    private UserService service;

    @Test
    public void run2(){
        service.save();
    }
}

run1()是成功的,run2()会出现空指针,resource和qualifier都试过了没用,怎么办求指导

run1()执行结果

d476c18d4e4731d749d9182f539e2361.png
run1

run2()执行结果

ebefbaf1a79c52f1167a3f9ff0bfcf5f.png
run2()

很多帖子博客上都说是因为使用了new对象,可是我也没有用啊。那是为什么呀,各位大佬帮帮孩子吧。


问题已解决,忘记启动IOC容器这件事了,我配置了前端控制器启动时加载spring问题解决。文章不删,钉在耻辱柱上。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值