Spring Boot SprinEL在Map中获取的值始终为空

lmyy7pcs  于 2023-02-22  发布在  Spring
关注(0)|答案(1)|浏览(207)

我想问的是,在使用springel的过程中,我想得到map中的值,但是无论我怎么得到,我的值总是null

@Data
@Component("workersHolder")
public class WorkersHolder {
    private Map<String, Integer> salaryByWorkers = new HashMap<>();

    public WorkersHolder() {

        salaryByWorkers.put("John", 35000);
        salaryByWorkers.put("Susie", 47000);
        salaryByWorkers.put("Alex", 12000);
        salaryByWorkers.put("George", 14000);
    }

    public static void main(String[] args) {
        // 35000
        System.out.println(new WorkersHolder().salaryByWorkers.get("John"));
    }

}
@Data
@Component
public class GetData {

    @Value("#{workersHolder.salaryByWorkers['John']}")
    private Integer johnSalary;

    @Value("#{workersHolder.salaryByWorkers['George']}")
    private Integer georgeSalary;

    @Value("#{workersHolder.salaryByWorkers['Susie']}")
    private Integer susieSalary;

    public static void main(String[] args) {
        // null
        // Hope this line can output 35000
       System.out.println(new GetData().johnSalary);
    }
}

粗体行打印的是35000,但是为空,请问有没有做错的地方,有什么想法欢迎提供给我,谢谢

nom7f22z

nom7f22z1#

尝试使用@Test代替public static void main(String[] args)进行单元测试,并且您的代码快照中的GetData不在spring ioc中,Spring无法管理它,因此spring el无效;

@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class GetDataTest{
    @Autowired
    private GetData getData;
    @Test
    public void test(){
        Assert.notNull(getData,"getData not be null");
        System.out.println(getData);

    }
}

如果您使用maven构建项目,您应该添加junitspring-test依赖项,建议在下面添加spring-test

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-test</artifactId>
      <version>2.1.3.RELEASE</version> // your spring version 
      <scope>compile</scope>
    </dependency>

相关问题