@Component无效注解
springboot 加载的时候,使用该注解的类一定要放在接口同级,或者下级包里面,不然是无法进行扫描的,比如接口放在com.xxx.yyy下面,而使用@component的类放在com.xxx.zzz下面,这样子是无法扫描的
如下图
所以要在启动类上添加扫描包注解@ComponentScan(basePackages = {“com.test.demo.server”})
@SpringBootApplication
@ServletComponentScan//防止 @WebListener 无效 @EnableScheduling
@ComponentScan(basePackages = {"com.test.demo.server"}) //说明要扫描的包
public class TestIpPortApplication {
//服务端
public static void main(String[] args) {
SpringApplication.run(TestIpPortApplication.class, args)
}
@Value取值取不到的几种情况总结:
application.properties 的配置方式
netty.server.port=8888
netty.server.url=127.0.0.1
application.yml的配置方式
netty:
port:9095
url:127.0.0.1
一、spring组件重写构造方法,在构造方法中引用@Value为null
int的变量默认值就为0 string类型 就为null
由于spring实例化顺序为先执行构造方法,再注入成员变量,所以序为先执行构造方法,再注入成员变量,所以ing实例化顺取值为null
解决办法为:再写一个常量类,在常量类中引用@value,再在构造方法中引用常量类的变量即可。
二,调用spring组件时使用new对象,而不是@Autowired(我碰到的问题)
使用对象来取得参数的时候,如果使用new创建对象,那么将取值为null。
创建对象的方法无法获取值,必须使用@Autowired注解。
/** 注入NettyServer */
@Autowired
private NettyServer nettyServer;
@Autowired
三,使用final或static修饰成员变量
四,spring mvc中引用@value为null
spring mvc是spring的子容器,需要在两个配置文件中都导入配置文件
<context:property-placeholder location=“classpath:jdbc.properties” ignore-unresolvable=“true”/>