Spring中JavaConfig特性

从Spring3開始,增加了JavaConfig特性。JavaConfig特性同意开发人员不必在Spring的xml配置文件里定义bean,能够在Java Class中通过凝视配置bean,假设你讨厌XML,那么这样的特性肯定是让你感到愉悦的。
当然,你仍然能够用经典的XML方法定义bean。JavaConfig仅仅是还有一个替代方案。
1) 编辑pom.xml引入依赖包CGLIB
在建立一个project后,编辑pom.xml文件要想使用JavaConfig特性。必须引入CGLIB包,引入后,才干够在Class配置bean(Class前加凝视@Configuration表示是一个Spring配置类)

 <!-- JavaConfig need cglib -->
    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib</artifactId>
        <version>2.2.2</version>
    </dependency>

2)编写几个Java Bean例如以下:

package com.spring.hello;
public interface IAnimal {
     public void makeSound();
}

package com.spring.hello;
public class Dog implements IAnimal{
    public void makeSound(){
        System.out.println("汪。汪。汪!");
    }
}

package com.spring.hello;
public class Cat implements IAnimal{
    public void makeSound(){
        System.out.println("喵!喵!喵!

"); } }

3)用JavaConfig特性配置Spring

<?

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-2.5.xsd"> <bean id="cat" class="com.spring.hello.Cat"/> <bean id="dog" class="com.spring.hello.Dog"/> </beans>

然而在JavaConfig方法,则通过使用凝视@Configuration 告诉Spring,这个Class是Spring的核心配置文件,相似于XML文件里的beans。而且通过使用凝视@Bean定义bean
我们在 com.spring.hello包内建立一个类。类名为AppConfig

package com.spring.hello;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
    @Bean(name="dog")
    public IAnimal getDog(){
        return new Dog();
    }
    @Bean(name="cat")
    public IAnimal getCat(){
        return new Cat();
    }
}

4)接下来使用App.java来測试

package com.spring.hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.spring.output.OutputHelper;
public class App {
    private static ApplicationContext context;
    public static void main(String[] args)
    {
        context = new AnnotationConfigApplicationContext(AppConfig.class);
        IAnimal obj = (IAnimal) context.getBean("dog");
        obj.makeSound();
        IAnimal obj2 = (IAnimal) context.getBean("cat");
        obj2.makeSound();
    }
}

输出结果例如以下:

这里写图片描写叙述

原文地址:https://www.cnblogs.com/mfmdaoyou/p/7161915.html