Spring中JavaConfig特性

    xiaoxiao2024-02-02  142

    从Spring3开始,加入了JavaConfig特性,JavaConfig特性允许开发者不必在Spring的xml配置文件中定义bean,可以在Java Class中通过注释配置bean,如果你讨厌XML,那么这种特性肯定是让你感到愉悦的。 当然,你仍然可以用经典的XML方法定义bean,JavaConfig只是另一个替代方案。 1) 编辑pom.xml引入依赖包CGLIB 在建立一个工程后,编辑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(); } }

    输出结果如下:

    最新回复(0)