组件扫描的使用步骤
1.建立工程拷贝配置文件spring 容器对应的配置文件和导入jar包(IOC和AOP)
2.在Spring容器中对用的配置文件中开启组件扫描
<context:component-scan base-package="包" />
3.在建立java类时 需要在java类上打对应的标注
@Repository 持久化层组件注解(DAO层)
@Service 业务层组件注解(调用DAO)
@Controller 控制层组件注解(sevlet)
@Component 通用层注解(除以上3中其他组件注解)
4.创建Spring 容器 从容器中获取对应的组件
applicationContext.xml文件
<?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"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">
<!-- 开启组件扫描 -->
<context:component-scan base-package="com.cn"></context:component-scan>
</beans>
Card类:
package com.cn.bean;
import org.springframework.stereotype.Component;
//@Component(value="cc")
@Component("cc")
public class Card {
@Override
public String toString() {
return "Card [suits=" + suits + ", points=" + points + "]";
}
public Card() {
super();
this.suits="黑桃";
this.points="A";
}
public String getSuits() {
return suits;
}
public void setSuits(String suits) {
this.suits = suits;
}
public String getPoints() {
return points;
}
public void setPoints(String points) {
this.points = points;
}
private String suits;
private String points;
}
Spring容器:
package com.cn.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.cn.bean.Card;
public class ApplicationContest {
public static void main(String[] args){
ApplicationContext app =
new ClassPathXmlApplicationContext("applicationContext.xml");
Card card = app.getBean("cc",Card.class);
System.out.println(card);
}
}