Spring框架是能够自动扫描、检查和预定义的项目并实例化bean,从而免去繁琐的bean类声明在xml文件中。
1、Bean类代码:
import org.springframework.stereotype.Repository;
@Repository
public class customDao {
@Override
public String toString() {
// TODO Auto-generated method stub
return "this is customDao";
}
}
2、Service类代码:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import mydao.*;
@Service
public class CustomeSer {
@Autowired(required=true)
private customDao customDao;
public void tt(){
System.out.print(customDao.toString());
;
}
}
3、配置xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
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-2.5.xsd
"
>
<bean
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<bean
class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
<context:component-scan base-package="mydao" />
<context:component-scan base-package="ser" />
</beans>
注:context:component-scan开启Spring自动扫描功能,base-package指存储组件,Spring框架自动扫描该文件夹,找出bean(注解@Component)并注册到Spring容器。
4、测试:
public class MyTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext context =
new ClassPathXmlApplicationContext("beans.xml");
CustomeSer s=(CustomeSer) context.getBean("customeSer");
s.tt();
}
}
注:
1、自定义自动扫描组件名称
默认是组件名称是类名首字母小写,其他不变。当然,也可以通过@Service("AA")指定组件的名称AA。
CustomerService cust = (CustomerService)context.getBean("AA");
扫描二维码关注公众号,回复:
2142842 查看本文章
2、自动组件扫描注解类型
- @Component – 指示自动扫描组件。
- @Repository – 表示在持久层DAO组件。
- @Service – 表示在业务层服务组件。
- @Controller – 表示在表示层控制器组件。
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {
String value() default "";
}
@Repository本质注解为@Component,Spring框架可以扫描所有的组件的@Component注解。但是,为了保持代码的阅读性,建议分层注解。