【问题标题】:Consider defining a bean of type考虑定义一个 bean 类型
【发布时间】:2021-11-25 16:19:39
【问题描述】:

我是 spring 的新手,我的目的是创建两个对象,一个对象打印一个字符串,第二个对象(与第一个对象有关联,取值 e 打印输出)。这是一个练习:

Helloworld.java 是这样的:

@Component
public class HelloWorld {
    
    private String message="";  


    public void setMessage(String message) {
        
        this.message = message;
        
    }


    @Bean
    public String getMessage() {
        return message;
    }

}

Person 类这样做:

@Component
public class Person {
    
    private String person="Jessy";
    
    public void setPerson(String person) {
        this.person = person;
    }
    
// I want receive hellowordbean and I want print the first message and join the two message
    @Autowired
    public String printMessage(HelloWorld message) {
        return message.getMessage()+" - "+this.person;
    }

}

这是主类:

@ComponentScan(value={"com.example.bean"})

public class TestApplication {

    public static void main(String[] args) {
        //SpringApplication.run(TestApplication.class, args);
        ApplicationContext context = SpringApplication.run(HelloWorld.class, args);
        HelloWorld word=context.getBean(HelloWorld.class);
        
        word.setMessage("hi world");
        
        ApplicationContext personContext = SpringApplication.run(Person.class, args);
        Person person=personContext.getBean(Person.class);
        person.setPerson("Jimbey");
        System.out.println(person.printMessage(word));
    }

}

我玩跑,我得到

说明:

com.example.bean.Person 中方法 printMessage 的参数 0 必需 找不到类型为“com.example.bean.HelloWorld”的 bean。

行动:

考虑在你的 配置

我不知道如何解决这个问题,有人可以帮助我吗?

【问题讨论】:

    标签: java spring spring-boot spring-data


    【解决方案1】:

    有很多问题:(我建议您阅读有关如何使用 Spring 构建 hello world 应用程序的教程。

    1. Person 类中的printMessage 方法中删除@Autowired 注释。这里可以看到@Autowired注解https://www.baeldung.com/spring-autowire的使用方法。

    2. TestApplication 类上使用@SpringBootApplication 注释。它创建所有带有@Component 注释的bean。

    【讨论】:

      猜你喜欢
      • 2018-08-03
      • 2019-12-05
      • 2018-06-22
      • 1970-01-01
      • 2022-06-17
      • 2020-08-01
      • 2019-02-14
      • 2018-12-21
      • 2019-05-10
      相关资源
      最近更新 更多