我们可以在springboot中将下面的类自动连接到Configuration类中吗

时间:2019-09-17 11:48:57

标签: java spring-boot spring-profiles

我有一个Component类和config类,所以我们可以在内部使用@value自动装配组件类吗,我尝试使用它,但是会抛出异常,有人可以帮助我理解

@Component
public class UserAction {
    @Value("${cp.user.name}")
    private String userName;

    @Value("${cp.user.actiontype}")
    private String actionType;

    @Value("${cp.user.designation}")
    protected Designation designation;

    public void show() {
        System.out.println(userName);
        System.out.println(actionType);
        System.out.println(designation);
    }
} 

@Configuration
@ComponentScan("com.example")
public class AppConfig {

@Autowired
UserAction userAction;
------
} 

所以我的问题是:我可以将我的UserAction bean自动连接到我的AppConfig类中吗? 我尝试使用它,但是它抛出异常,因此我们可以自动装配内部使用@value的组件吗:

    
Unable to start web server; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'AppConfig ': Unsatisfied dependency expressed through field 'userAction'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userAction': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'cp.user.actiontype' in value "${cp.user.actiontype}"

1 个答案:

答案 0 :(得分:1)

是的,您可以在Configuration类中使用Autowire bean,但是这里的问题是您的bean中的属性在properties/yml文件中没有设置值

@Value("${cp.user.actiontype}")

在.properties或.yml文件中设置属性cp.user.actiontype