(笔记)Spring实战_最小化Spring XML配置(4)_使用Spring基于Java的配置

来源:互联网 发布:网络售药 京东 编辑:程序博客网 时间:2024/05/21 22:51

1.创建基于Java的配置
<context:component-scan>也会自动加载使用@Configuration注解所标注的类。

<?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.xsd         http://www.springframework.org/schema/context         http://www.springframework.org/schema/context/spring-context.xsd">    <context:component-scan base-package="com.springinaction.springgod" /></beans>

2.定义一个配置类
在基于Java的配置里使用@Configuration注解的Java类,就等价于XML配置中的<beans>元素。

package com.springinaction.springgod;import org.springframework.context.annotation.Configuration;@Configurationpublic class SpringGodConfig{}

@Configuration注解会作为一个标识告知Spring:这个类将包含一个或多个Spring Bean的定义。这些Bean的定义是使用@Bean注解所标注的方法。
3.声明一个简单的Bean

    @Bean    public Performer duke()    {        return new Juggler();    }

@Bean告知Spring这个方法将返回一个对象,该对象应该被注册为Spring应用上下文中的一个Bean。方法名作为该Bean的ID。在该方法中所实现的所有逻辑本质上都是为了创建Bean。
在XML配置中,Bean的类型和ID都是由String属性来标示的。String标识符的缺点是它们无法进行编译期检查。在Spring的基于Java的配置中,并没有String属性。Bean的ID和类型都被视为方法签名的一部分。Bean的实际创建是在方法体中定义的。因为它们全部是Java代码,所以我们可以进行编译期检查来确保Bean的类型是合法类型,并且Bean的ID是唯一的。
参考:http://blog.csdn.net/home_zhang/article/details/8880858

        <dependency>            <groupId>cglib</groupId>            <artifactId>cglib-nodep</artifactId>            <version>3.2.4</version>        </dependency>

4.使用Spring的基于Java的配置进行注入
构造器注入

    @Bean    public Performer duke15() {        return new Juggler(15);    }

setter注入

    @Bean    public Instrument saxphone()    {        return new Saxophone();    }    @Bean    public Performer kenny()    {        Instrumentalist kenny = new Instrumentalist();        kenny.setSong("Jingle Bells");        kenny.setInstrument(saxphone());        return kenny;    }

为Bean装配另一个Bean的引用

    @Bean    public Poem sonnet29()    {        return new Sonnet29();    }    @Bean    public Performer poeticDuke()    {        return new PoeticJuggler(sonnet29());    }

通过声明方法引用一个Bean并不等同于调用该方法。

0 0