Spring IOC,xml配置文件,xml+註解,純註解的方式,聲明Bean

一,採用純XML配置文件

在spring 2.5前,使用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:p="http://www.springframework.org/schema/p"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
		http://www.springframework.org/schema/mvc
		http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!-- 包掃描 -->
    <context:component-scan base-package="com.XXX.XX">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
    </context:component-scan>
    <!-- aop支持 -->
    <aop:aspectj-autoproxy proxy-target-class="true"/>

    <mvc:annotation-driven/>
    <!-- 註解說明 -->
    <mvc:interceptors>
        <bean class="com.XXX.XX.admin.interceptor.AdminAuthInterceptor"/>
    </mvc:interceptors>
    <!--上傳文件所需要的bean-->
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
          p:defaultEncoding="utf-8"/>
    <!-- 配置數據源 -->
    <bean id="baseDataBase" class="com.alibaba.druid.pool.DruidDataSource"
          destroy-method="close">
        <property name="url" value="${druid.url}"/>
        <property name="username" value="${druid.username}"/>
        <property name="password" value="${druid.password}"/>
        <property name="driverClassName" value="${druid.driverClassName}"/>
        <property name="filters" value="${druid.filters}"/>
    </bean>
    <bean id="user" class="com.XXX.XX.entity.User">
        <property name="id" value="1" />
        <property name="name" value="zhangsan" />
    </bean>
</beans>

二。XML+ 註解的方式

在Spring 2.5以後,加入了註解,主要是SSM框架

主要是用@開頭進行標註, 最重要的 @component,查看源碼,

/** Target裏面放數組,ElementType使用的範圍,
    TYPE,  類,接口,註解,enum
    FIELD,  用於描述域
    METHOD, 方法上
    PARAMETER,  參數
    CONSTRUCTOR,  構成器
    LOCAL_VARIABLE, 局部變量
    ANNOTATION_TYPE,
    PACKAGE,  包名
 */
@Target({ElementType.TYPE})
/** Retention 聲明在什麼時候生效
    SOURCE,  只保留在源文件,.java
    CLASS,   保留在編譯後的 class文件
    RUNTIME  .java .class 都包含
**/
@Retention(RetentionPolicy.RUNTIME)
//註解標記元素的註解信息包含在javadoc中
@Documented
public @interface Component {
    String value() default "";
}

在開發的過程中, 目錄結構會新建controller,service,dao三層結構,對應@Controller@Service,@Repository三個註解。 其實點擊源碼,發現這三個註解底層也是用的@Component註解

1. 新建項目,在resource 目錄下新建spring.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"
       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">

    <!-- 包掃描 根據類型包含或者不包含,type=annotation , aspectj,assignable  -->
    <context:component-scan base-package="com.study"  >
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>
    <!--<bean id="userController" class="com.study.controller.UserController"/>-->
</beans>

2,新建路徑com.study.admin.controller 下的類 UserController, 添加上面四種註解中的一種

3,添加測試類 UserTest,都能打印結果,說明類已經加載IOC容器中,

public class UserTest {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("spring.xml");
        //使用類型可以獲取到bean
        UserController bean = ioc.getBean(UserController.class);
        System.out.println(bean);
    }
    @Test
    public void test1() {
        ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("spring.xml");
        //根據名稱,首字母小寫,也可以獲取bean
        UserController bean = (UserController) ioc.getBean("userController");
        System.out.println(bean);
    }
}

4,新建service接口 com.study.admin.service.BaseService  和實現類 com.study.admin.service.impl.UserImpl, dao層數據類  com.study.admin.dao.UserDao。

在controller層,通過@Autowired 調用service實現業務邏輯,這裏的Autowired首先通過類型匹配,其次通過名字匹配,

4.1,注入的時候是接口,那麼會自動找到實現類,但是如果實現類有多個,這裏就會報錯,

controller 層
@Controller
public class UserController {

    /**
     * 1,如果BaseService只有一個實現類,是正常
     * 2,如果有兩個實現類,的解決方案
     *   2.1,後面申明的名稱,換成對應的類名稱就可以( @Autowired BaseService userService;)
     *   2.2, 類注入service 加上對應名稱 @Service("baseService"), 
     *   2.3,@Autowired 下面再加註解 @Qualifier("userService")
     *   2.4  在其中一個實現類加上 @Primary
     *
     *   Resource 和 Autowired 的區別
     *   Autowired spring裏面的包,優先類型匹配,然後再名稱匹配
     *   Resource 是JDK的包,優先名字匹配,然後類型匹配
     */
    @Autowired
    BaseService baseService;

    public void test() {
        baseService.getDate();
    }
}

//service 層
//接口
public interface BaseService {

    void getDate();
}
//實現類
@Service
public class RoleService implements BaseService {
    @Override
    public void getDate() {
        System.out.println("roleService get data");
    }
}

@Service
public class UserService implements BaseService {

    @Override
    public void getDate() {
        System.out.println("userService get data");
    }
}

三,純註解的方式,Javaconfig

從spring 3.0 開始,基本使用spring boot 來開發,無xml配置文件

1. 使用@configuration 註解代替XML,  @ComponentScan代替包掃描,

2,@Bean 用來申明外部Bean,需要自己new然後返回,方法名就是IOC中存的名字

3.使用 @PropertySource("db.properties") 映入外部配置文件,@Value("${mysql.name}") 獲取值,${} 根據名稱獲取值,#{} 獲取對象的屬性值

小結:

本篇主要講解了, 由 xml配置到純註解的方式, xml中有的,都會有對應的註解可以代替

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章