spring中将类加入到IOC容器中的方法有两种:
1.在IOC容器中配置bean
这里是在IOC容器中配置bean的方法,使用的是set注入的方法。
<bean id="student" class="ora.awen.entity.Student" >
<!-- property:该class所代表的类的属性
name:属性名
value:属性值
-->
<property name="stuNo" value="2"></property>
<property name="stuName" value="ls"></property>
<property name="stuAge" value="24"></property>
<property name="course" ref="courseid"></property>
</bean>
<bean id="courseid" class="ora.awen.entity.Course">
<property name="courseName" value="liuhao"></property>
<property name="courseTime" value="200"></property>
</bean>
2.通过注解的方式将其类加入到IOC容器中。
通过注解的方式加入到IOC容器中,下面的代码就是将这些类加入到IOC容器中的方法,
a.需要在xml中配置一个扫描器:
<context:component-scan base-package="org.awen.controll"></context:component-scan>
b.还有另一种方法,在一个配置类中加入扫描器
配置类的代码在下面,
@ComponentScan其中在这里也可以选择将哪一个类配置到其中 也可以选择将哪一个类不配置其中
在这里又有三个方法,分别是excludeFilters,includeFilters,还有一个是自定义的方法。
//这个是排除Servcice 和Controller层
//@ComponentScan(value=“org.awen”,excludeFilters= {@ComponentScan.Filter(type=FilterType.ANNOTATION,value= {Service.class,Controller.class})})
//这个是包括某些类的使用方法,需要设置默认行为,才可以。
//@ComponentScan(value=“org.awen”,includeFilters= {@ComponentScan.Filter(type=FilterType.ANNOTATION,value= {Service.class})},useDefaultFilters=false)
type=FilterType.ANNOTATION这个针对于三层注解类型
但是ASSIGNABLE_TYPE:具体得类
区分:
ANNOTIATION:Controller.class 值得是所有标有Controller的类。
ASSIGNABLE_TYPE:具体得类
自定义
CUSTON 然后后面跟你的类名加.class 这个是你自己自定义的类 必须实现一个接口
excludeFilters:排除
includeFilters:有默认行为可以通过useDefaultFilters=false禁止默认行为
还有一个自定义的方法
自定义代码为:
public class MyFilter implements TypeFilter{
@Override
public boolean match(MetadataReader metadataReader, MetadataReaderFactory arg1) throws IOException {
// TODO 自动生成的方法存根
ClassMetadata classMetadata=metadataReader.getClassMetadata();
//扫描器 扫描“org.awen”包中所有的类,getClassName()而可以拿到 该包中所有的类
String className=classMetadata.getClassName();
//只过滤出 和学生相关的三层组件 把有学生的三层组件纳入到IOC容器中,这个也就是 将所有包含Student的类纳入到IOC中。
if(className.contains("Student")) {
return true;
}
return false;
}
}
代码为:
//在这里三个例子,分别为Dao层代码,Service层代码,Controller层代码
@Service
public class StudentService {
}
@Controller
public class StudentController {
}
@Repository
public class StudentDao {
}
//在这里显示配置类的代码
//这个会默认将配置类纳入其中
@Configuration
@ComponentScan
public class MyConfig {
}