The method will be added to a class spring IOC container in two ways:
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. By way of its class annotation is added to the vessel IOC.
通过注解的方式加入到IOC容器中,下面的代码就是将这些类加入到IOC容器中的方法,
a.需要在xml中配置一个扫描器:
<context:component-scan base-package="org.awen.controll"></context:component-scan>
b.还有另一种方法,在一个配置类中加入扫描器
配置类的代码在下面,
@ComponentScan其中在这里也可以选择将哪一个类配置到其中 也可以选择将哪一个类不配置其中
在这里又有三个方法,分别是excludeFilters,includeFilters,还有一个是自定义的方法。
// This is the Controller and the negative Servcice layer
//@ComponentScan(value="org.awen",excludeFilters= {@ ComponentScan.Filter (type = FilterType.ANNOTATION , value = {Service.class, Controller.class})})
// This is the method involving the use of certain types, you need to set the default behavior before they can.
//@ComponentScan(value="org.awen",includeFilters= {@ ComponentScan.Filter (type = FilterType.ANNOTATION , value = {Service.class})}, useDefaultFilters = false)
type = FilterType.ANNOTATION in this for three types of annotations
but ASSIGNABLE_TYPE: get specific class
distinction:
ANNOTIATION: Controller.class is worth all marked with the Controller class.
ASSIGNABLE_TYPE: Specific class was
custom
CUSTON then followed by class name plus your .class this is your own custom class must implement an interface
excludeFilters: exclude
includeFilters: There are default behavior can prevent the default behavior useDefaultFilters = false
There is also a custom method
自定义代码为:
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;
}
}
Code:
//在这里三个例子,分别为Dao层代码,Service层代码,Controller层代码
@Service
public class StudentService {
}
@Controller
public class StudentController {
}
@Repository
public class StudentDao {
}
//在这里显示配置类的代码
//这个会默认将配置类纳入其中
@Configuration
@ComponentScan
public class MyConfig {
}