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

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;


@Configuration
public 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值