@org.springframework.beans.factory.annotation.Autowired(required=true),@Autowired报错以及解决方案详解,构造函数使用简介

构造函数使用简介请看第四点的ModelGG

Autowired 报错

错误内容如下:

***************************
APPLICATION FAILED TO START
***************************

Description:

Field gg in com.sq.statistics.service.test.EE required a bean of type 'com.xxx.xxxx.xxx.xxx' that could not be found.

The injection point has the following annotations:
	- @org.springframework.beans.factory.annotation.Autowired(required=true)

The following candidates were found but could not be injected:
	- User-defined bean method 'setGG' in 'modelFF' ignored as the bean value is null

说明:

@Autowired 一般用来自动装配,但是需要对象注册成bean(有对应实例)。。

可以装配的举例:

1.带有@service的类

会自动注入,注册成bean

2. 带有@Component的类

会自动注入,注册成bean

3.带有@Configuration的类

会自动注入,注册成bean

4. new 出来的对象(需要在一开始就实例化,注册成bean)

下面是详细案例

  • 目录结构
- ModelGG  还讲解了有参构造和无参构造
- ModelFF
- ModelEE
  • 以下是new 出来的对象,被autowired的一个案例。。。差点以为没有实例化

ModelGG - 被new的对象,需要被装配的对象。。

package com.sq.statistics.service.test;

public class ModelGG {
    private static String attribute = "123";//这个属性不能用有参构造变更
    public ModelGG() {
        System.out.println("无参构造方法,和类名同名,在类实例化时调用方法,调用了有参就不会调用无参");
    }
    public ModelGG(String attribute) {
        System.out.println("有参构造方法,和类名同名,在类实例化时调用方法,可以传参赋值类里边的属性。(必须要有无参构造才可以有有参构造),调用了有参就不会调用无参");
        this.attribute = attribute;
    }
    public void setAttribute(String attribute) {
        this.attribute = attribute;
    }
    public void printGGAttribute() {//打印这个类的属性
        System.out.println(attribute);
    }
}

ModelFF - 此处在程序一开始就 将对象new出来了,有对应的实例了,所以可以对ModelGG进行autowired

package com.sq.statistics.service.test;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration //自动注入,程序一开始就注册实例
public class ModelFF {

    @Bean //自动注入,会自动调用
    public ModelGG setGG() {
//        return new ModelGG("gg-gg-gg-gg-gg-gg");
        ModelGG gg = new ModelGG();	
        gg.setAttribute("gg-gg-gg-gg-gg-gg");
        return gg;
    }
}


autowired 了ModelGG

package com.sq.statistics.service.test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component //自动注入,程序一开始就注册实例
public class ModelEE {

    @Autowired
    private ModelGG gg;

    @PostConstruct//bean注入完成后会运行
    public void startWithGG() {
        gg.printGGAttribute();
    }
}

在一个已经注入的类中,@Bean注解,然后new一个对象,,,这个对象,也可以被Autowired

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值