问题
解决方案
@Repository
public class SequenceDaoImpl implements SequenceDao {
... ...
}
可以在使用component scan的同时,使用@Autowired进行注入
<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-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.apress.springrecipes.sequence" />
</beans>
Filtering Components
Table 4.5. Filter Types
Filter Type | Example Expression | Description |
---|---|---|
annotation | org.example.SomeAnnotation | An annotation to be present at the type level in target components. |
assignable | org.example.SomeClass | A class (or interface) that the target components are assignable to (extend/implement). |
aspectj | org.example..*Service+ | An AspectJ type expression to be matched by the target components. |
regex | org\.example\.Default.* | A regex expression to be matched by the target components class names. |
custom | org.example.MyTypeFilter | A custom implementation of the org.springframework.core.type .TypeFilter interface. |
<beans ...>
<context:component-scan base-package="com.apress.springrecipes.sequence">
<context:include-filter type="regex"
expression="com\.apress\.springrecipes\.sequence\..*Dao.*" />
<context:include-filter type="regex"
expression="com\.apress\.springrecipes\.sequence\..*Service.*" />
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
</beans>
对扫描到的Componet进行命名
@Repository
public class SequenceDaoImpl implements SequenceDao {
... ...
}
在容器中的名称为sequenceDaoImpl。
@Service("sequenceService")
public class SequenceService {
...
}
@Repository("sequenceDao")
public class SequenceDaoImpl implements SequenceDao {
...
}
<beans>
<context:component-scan base-package="org.example"
name-enerator="org.example.MyNameGenerator"/>
</beans>
指定Component的Scope
@Scope("prototype")
@Repository
public class MovieFinderImpl implements MovieFinder {
// ...
}
Table 4.3. Bean scopes
Scope | Description |
---|---|
singleton | (Default) Scopes a single bean definition to a single object instance per Spring IoC container. |
prototype | Scopes a single bean definition to any number of object instances. |
request | Scopes a single bean definition to the lifecycle of a single HTTP request; that is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring |
session | Scopes a single bean definition to the lifecycle of an HTTP |
global session | Scopes a single bean definition to the lifecycle of a global HTTP |