国王陛下万万岁

导航

 

1.回顾以下我们用xml文件配置spring的方法,用标签定义了一个java类,或者说是java bean。用标签给java bean当中的属性赋值。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="bookDao" class="com.oxygen.dao.impl.BookDaoImpl" >
        <property name="name" value="AdminUser01"/>
    </bean>
</beans>

 

@Component注解
用注解开发,我们用@Component这个属性来指代xml配置文件当中的<bean>标签。
如上个示例中,我们用<bean>标签,定义了一个id="bookDao"的bean,在Spring注解开发当中,我把@Component注解放在BookDaoImpl类上,通过这种方式告诉Spring,这是一个bean类。
@Component里面的值"bookDao"是给这个bean取个名字,默认可以不填写。

package com.oxygen.dao.impl;

import com.oxygen.dao.BookDao;
import org.springframework.stereotype.Component;

@Component (   "bookDao" )
public class BookDaoImpl    implements BookDao {

    public void save() {
        System.out.println(   "Book Dao Save..." );

    }
}  

 

我们用@Component注解标注了BookDaoImpl类,但Spring并不知道这个类,我们需要采用一种方式让Spring把我们标注@Component注解的类当中bean来管理。
这里,我们先用Spring的XML配置文件来明确告诉Spring去管理@Component标注的类。 

<   context:component-scan base-package="com.oxygen.dao.impl"/>是告诉spring去某个包里扫描@Component注解坚持的类

<   beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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.xsd">

    <   context:component-scan base-package="com.oxygen.dao.impl"/>


 componen-scan就是让Spring去扫描知道包里面的所有java 类。

注意:
本文目前还是注解和xml配置混合在使用。
对Dao类使用了@Component注解
对于Spring容器的核心配置使用了xml配置
Spring给@Component注解提供了3个衍生注解,这三个注解与@Component注解的作用完全一样,只是意义更明确.

@Controller :用于定义表现层bean
@Service :用于定义业务层bean
@Reponsitory :用于定义数据层bean

 

在纯注解开发模式下,获取Spring容器的方法:AnnotationConfigApplicationContext

package com.oxygen;

import com.oxygen.config.SpringConfig;
import com.oxygen.dao.BookDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class App
{
    public static void main( String[] args )
    {

        ApplicationContext ctx=new AnnotationConfigApplicationContext(SpringConfig.class);
        BookDao bookDao= (BookDao) ctx.getBean("bookDao");
        bookDao.save();
    }
}

 

posted on 2022-10-22 21:07  国王陛下万万岁  阅读(475)  评论(0编辑  收藏  举报