[英]How to create spring bean that can be autowired using annotations?
我有一個小型 MVC web 應用程序,其中 Controller 使用注釋配置。
xml 設置很簡單。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="net.dynamic_tools.jsdependency" />
</beans>
我的 controller 看起來像
@Controller
@RequestMapping("/*")
public class JSDependencyController {
@Autowired
private ScriptTagsJSView scriptTagsJSView;
我收到一條錯誤消息
沒有為依賴項找到類型為 [net.dynamic_tools.jsdependency.view.ScriptTagsJSView] 的匹配 bean
我嘗試向 ScritTagsJSView 添加組件注釋
@Component("scriptTagsJSView")
public class ScriptTagsJSView implements View {
沒有運氣。 我還嘗試添加配置 POJO 並使用 @Bean 注釋
@Configuration
public class Config {
@Bean
public ScriptTagsJSView getScriptTagsJSView() {
return new ScriptTagsJSView();
}
我可能遺漏了一些相當簡單的東西,但我不明白為什么這不起作用。 有任何想法嗎?
我認為您可能只需要在 xml 中使用<context:annotation-config/>
。
首先,您要使用注釋驅動標簽。 這將確保 Spring 實例化所有使用 @Controller、@Repository、@Service 和 @Component 注釋的類
<mvc:annotation-driven />
您還需要組件掃描,但您已經擁有它。
您可能還想避免為您的 Bean 命名,因為 spring 將僅根據類型進行匹配。 (不要使用@Component("scriptTagsJSView") 而只是@Component)
最后,您需要在需要注入的地方添加@Autowired。 我個人只將它與構造函數結合使用。
public class JSDependencyController {
@Autowired
public JSDependencyController(ScriptTagsJSView view){
this.view = view;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.