@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


版权声明:本文为weixin_43329956原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。