DecadeAnkle / JavaStudyRecord

Java学习内容汇总
0 stars 0 forks source link

@Autowired的认知 #1

Open DecadeAnkle opened 11 months ago

DecadeAnkle commented 11 months ago

@Autowired的认知

@Component,@Service这种注解生成的实例被注入到spring容器进行管理后,需要用@Autowired来使用,不能直接new出来,不然没有从properties中读取数据

@Component
@Slf4j
@PropertySource({"classpath:nettyServer.properties"})
public class NettyServer {
    @Value("${netty.server.port}")
    private int port;
    @Value("${netty.server.soBacklog}")
    private int soBacklog;
    @Value("${netty.server.soKeepAlive}")
    private boolean soKeepAlive;
}

@Autowired的使用推荐

  1. 推荐用构造方法注入 在 Spring 4.3 及以后的版本中,如果这个类只有一个构造方法,那么这个构造方法上面也可以不写 @Autowired 注解

    
    public class Car {
    
    private final Wheel wheel;
    
    public Car(Wheel wheel) {
        Assert.notNull(wheel,"Wheel must not be null");
        this.wheel = wheel;
    }
    
    public void run() {
        wheel.roll();
    }

}


2.基于属性的注入,本质上是通过反射的方式直接注入到field
```java
public class Car {

    @Autowired
    private Wheel wheel;

    public void run() {
        wheel.roll();
    }
}

问题所在就是第二种方法会出现NPE

Car car = new Car();
car.run();// -> NullPointerException

3.初始化顺序的不同会导致NPE

private Person person;

private String company;

public UserServiceImpl(){

    this.company = person.getCompany();
}

具体看另一个issue 静态变量或静态语句块 –> 实例变量或初始化语句块 –> 构造方法 -> @Autowired 的顺序 所以在执行这个类的构造方法时,person 对象尚未被注入,它的值还是 null。

DecadeAnkle commented 11 months ago

参考