spring注解不支持静态变量注入

spring注解不支持静态变量注入:今天敲代码  自动配置 配置:

Animal.java
 1 package study01_autoconfig.beanConfig;
 2 
 3 import org.springframework.stereotype.Component;
 4 
 5 @Component
 6 public class Person implements Animal{
 7     private String name;
 8     
 9     public void talk() {
10         name="linhua";
11         System.out.println("hi I'm "+name);
12     }
13 }
Person.java继承Anima
 1 package study01_autoconfig.beanConfig;
 2 
 3 import org.springframework.context.annotation.ComponentScan;
 4 import org.springframework.context.annotation.Configuration;
 5 
 6 @ComponentScan
 7 @Configuration
 8 public class PersonConfig {
 9     
10 }
配置类

测试类:

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注解不支持静态变量注入

猜你喜欢

转载自www.cnblogs.com/shaoxiaohuan/p/11042614.html