@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的使用推荐
推荐用构造方法注入
在 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();
}
@Autowired的认知
推荐用构造方法注入 在 Spring 4.3 及以后的版本中,如果这个类只有一个构造方法,那么这个构造方法上面也可以不写 @Autowired 注解
}
问题所在就是第二种方法会出现NPE
3.初始化顺序的不同会导致NPE
具体看另一个issue 静态变量或静态语句块 –> 实例变量或初始化语句块 –> 构造方法 -> @Autowired 的顺序 所以在执行这个类的构造方法时,person 对象尚未被注入,它的值还是 null。