Spring 将接口传递给控制器构造函数时出现问题
我是春天的新手。下面是我面临的问题。请帮忙 在启动开发工具时,我得到以下错误 tacos.web.DesignTacoController中构造函数的参数0需要找不到类型为“taco.data.IngredEnterpository”的bean 行动: 考虑在配置中定义“taco.data.IngredEnterpository”类型的bean IngredEnterpository.javaSpring 将接口传递给控制器构造函数时出现问题,spring,spring-boot,spring-jdbc,Spring,Spring Boot,Spring Jdbc,我是春天的新手。下面是我面临的问题。请帮忙 在启动开发工具时,我得到以下错误 tacos.web.DesignTacoController中构造函数的参数0需要找不到类型为“taco.data.IngredEnterpository”的bean 行动: 考虑在配置中定义“taco.data.IngredEnterpository”类型的bean IngredEnterpository.java package taco.data; import tacos.Ingredient; publi
package taco.data;
import tacos.Ingredient;
public interface IngredientRepository {
Iterable<Ingredient> findAll();
Ingredient findOne(String id);
Ingredient save(Ingredient ingredient);
}
package taco.data;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import tacos.Ingredient;
@Repository
public class JdbcIngredientRepository implements IngredientRepository {
private JdbcTemplate jdbc;
@Autowired
public JdbcIngredientRepository (JdbcTemplate jdbc) {
this.jdbc = jdbc;
}
@Override
public Iterable<Ingredient> findAll() {
return jdbc.query("SELECT ID, NAME, TYPE FROM INGREDIENT", this::mapRowToIngredient);
}
@Override
public Ingredient findOne(String id) {
return jdbc.queryForObject("SELECT ID, NAME, TYPE FROM INGREDIENT WHERE ID=?", this::mapRowToIngredient, id);
}
@Override
public Ingredient save(Ingredient ingredient) {
jdbc.update("INSERT INTO INGREDIENT VALUES (?,?,?)", ingredient.getId(), ingredient.getId(), ingredient.getType());
return ingredient;
}
private Ingredient mapRowToIngredient(ResultSet rs, int rowNum)
throws SQLException {
return new Ingredient(rs.getString("id"), rs.getString("name"), Ingredient.Type.valueOf(rs.getString("type")));
}
}
问题
TacoCloudApplication
没有看到任何@组件
(@存储库
是在tacos
包之外定义的@组件
)
发件人:
可以使用单个@springbootplication
注释来启用这三个功能,即:
:启用Spring Boot的自动配置机制@EnableAutoConfiguration
:在应用程序所在的包上启用@ComponentScan
扫描@Component
:允许在上下文中注册额外的bean或导入其他配置类@Configuration
tacos
包下面定义的@组件
s
解决方案
将jdbcingeridentrepository
移动到以tacos
开头的包中
使您的应用程序结构成为:
└── tacos
├── data
│ ├── IngredientRepository.java
│ └── JdbcIngredientRepository.java
├── Ingredient.java
├── Order.java
├── TacoCloudApplication.java
├── Taco.java
└── web
├── DesignTacoController.java
├── OrderController.java
└── WebConfig.java
或添加
@ComponentScans(
value = {
@ComponentScan("tacos"),
@ComponentScan("taco")
}
)
到TacoCloudApplication
类
另见:
└── tacos
├── data
│ ├── IngredientRepository.java
│ └── JdbcIngredientRepository.java
├── Ingredient.java
├── Order.java
├── TacoCloudApplication.java
├── Taco.java
└── web
├── DesignTacoController.java
├── OrderController.java
└── WebConfig.java
@ComponentScans(
value = {
@ComponentScan("tacos"),
@ComponentScan("taco")
}
)