2
我無法把他們放在一起:如何使用@Named註解從Spring 3.0中的屬性注入構造函數參數?
<?xml version="1.0" encoding="UTF-8"?>
<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:property-placeholder location="classpath:some-useful.properties"/>
<context:component-scan base-package="scan.me.scotty"/>
</beans>
主要是這樣的:
@Named
@Singleton
public class MySpringMain {
@Inject
public MySpringMain(final AReallyCool component) {
component.runForAWhile();
}
public static void main(final String... args) {
new ClassPathXmlApplicationContext(args);
}
}
組件是這樣的:
@Named
public class AReallyCool {
@Inject
public AReallyCool(@Named("whoAmI") final String whoAmI) {
// do something here
}
}
和屬性是:
whoAmI=Who is anyone, really?
當然(對我來說)春死的死
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [java.lang.String] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.inject.Named(value=whoAmI)}
問題:
- 這甚至一個合理的做法?我試圖避免特定於Spring的註釋。
- 你會如何做這項工作?
答案太長。你可以指定他應該使用'Value'而不是'Named'。無論如何。但要擺脫'@ ImportResource'。它不是必需的,並且應該主要用於'@ Configuration'類。 – Bozho 2010-12-16 06:43:44
它與@Value正常工作。我正在尋找@Named的解決方案。 – binkley 2010-12-16 14:57:45
@Bozho我對長度不以爲然,我總是發現有用的例子。感謝您與@ImportResource的評論,點好了。 – Bill 2010-12-16 15:30:08