本文主要讲述使用Config配置文件来代替xml配置文件,Config配置文件和xml配置文件功能一模一样,xml配置可能相对繁琐,每次要去官网拷贝外面的一层
背景:一人一猫一狗
猫类
package com.kuangstudy.pojo; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; /** * 功能描述 * * @since 2022-06-26 */ @Component @Scope("prototype") public class Cat { public void shout() { System.out.println("miao~"); } }
狗类
package com.kuangstudy.pojo; import org.springframework.stereotype.Component; /** * 功能描述 * * @since 2022-06-26 */ @Component public class Dog { public void shout() { System.out.println("wang~"); } }
人类
package com.kuangstudy.pojo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; /** * 功能描述 * * @since 2022-06-26 */ @Component @Scope("prototype") public class Person { @Value("xiaohong") private String name; @Autowired(required = false) private Cat cat; // @Autowired private Dog dog; public String getName() { return name; } public void setName(String name) { this.name = name; } public Cat getCat() { return cat; } public void setCat(Cat cat) { this.cat = cat; } public Dog getDog() { return dog; } public void setDog(Dog dog) { this.dog = dog; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", cat=" + cat + ", dog=" + dog + '}'; } }
配置类
package com.kuangstudy.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; /** * 功能描述 * * @since 2022-06-29 */ @Configuration @ComponentScan("com.kuangstudy.pojo") public class AppConfig { // @Bean // public Person getPerson() { // return new Person(); // } }
测试类
import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import com.kuangstudy.config.AppConfig; import com.kuangstudy.pojo.Person; /** * 功能描述 * * @since 2022-06-29 */ public class Test1 { @Test public void test1() { ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); Person person = context.getBean("person", Person.class); System.out.println(person.getName()); person.getCat().shout(); person.getDog().shout(); } }
结果
xiaohong miao~ wang~
getPerson
bean,也可以运行成功,这里涉及到@Bean的用法,不过@Bean不这样使用,而是用来获取一些Resource资源