@Autowired并不适用于方法参数

时间:2017-11-15 01:10:26

标签: spring spring-boot dependency-injection kotlin

这是我的AppConfig:

@Configuration
@EnableWebMvc
@ComponentScan
class AppConfig{
    @Bean("myname")
    fun name(): Name = Name("Quang")
}

数据类:

data class Name(val value: String ="")

我的控制器类:

@Controller
@RequestMapping("/")
class Main{
    @RequestMapping("/")
    @ResponseBody
    fun index(@Autowired @Qualifier("myname") name: Name): Name {
        //this return ""
        return name
    }
}

结果是""而不是" Quang"。 但是现在如果我从这样的字段中注入它,它可以正常工作:

@Controller
@RequestMapping("/")
class Main{
    @Autowired(required = true)
    @Qualifier("myname")
    lateinit var name:Name
    @RequestMapping("/")
    @ResponseBody
    fun index(): Name {
        //this return "Quang" as expected
        return name
    }
}

那么你能解释为什么@Autowired在方法参数

中使用它时不起作用

1 个答案:

答案 0 :(得分:0)

根据文件:

  

标记构造函数,字段,setter方法或配置方法   由Spring的依赖注入工具自动启动。

在你的第一个例子中,Spring不会自动装配任何东西。