spring注解不支持静态变量注入:今天敲代码 自动配置 配置:
Animal.java
package study01_autoconfig.beanConfig; import org.springframework.stereotype.Component; @Component
public class Person implements Animal{
private String name; public void talk() {
name="linhua";
System.out.println("hi I'm "+name);
}
}
Person.java继承Anima
package study01_autoconfig.beanConfig; import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; @ComponentScan
@Configuration
public class PersonConfig { }
配置类
测试类:
package study01_autoconfig.beanConfig; import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class) //不写这个会报错。。。。。
@ContextConfiguration(classes=PersonConfig.class)
public class PersonTest {
@Autowired
//spring annotation不支持静态变量注入 static Person per; //当为静态变量注入时,会报Autowired annotation is not supported on static fields
@Test
public void test1() {
per.talk();
}
//不能在main方法里面,否则会报空指针
/*public static void main(String[] args) {
per.talk();
}*/ }
然后发现 ,spring注解不支持静态变量注入