构造函数使用简介请看第四点的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() {
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
public void startWithGG() {
gg.printGGAttribute();
}
}
在一个已经注入的类中,@Bean注解,然后new一个对象,,,这个对象,也可以被Autowired
|