application.xml <?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 https://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="aService" class="com.test.learnjava.service.AService"> <property name="bService" ref="bService" /> <!-- 注入另外一个bean --> <property name="username" value="test" /> <!-- 注入int、String 等数据类型 --> </bean> <bean id="bService" class="com.test.learnjava.service.BService" /> </beans>
// 建立上下文 ApplicationContext context = new ClassPathXmlApplicationContext("application.xml"); // 获取Bean AService aService = context.getBean(AService.class); // 正常调用 aService.test();
@Component public class BService { ... }
@Component 注解就至关于定义了一个Beanjava
使用 @Autowired 就至关于把指定类型的Bean注入到指定的字段中。和XML配置相比,@Autowired大幅简化了注入,由于它不但能够写在set()方法上,还能够直接写在字段上,甚至能够写在构造方法中web
@ComponentScan 标注的类代表是一个配置类,做用相似一个 .xml 配置文件。但要与 @ComponentScan 一块儿使用,目的是扫描涉及到的beanspring
若是一个Bean不在咱们本身的package管理之类,例如ZoneId,如何建立它?app
答案是:咱们本身在@Configuration类中编写一个Java方法建立并返回它,注意给方法标记一个@Bean注解:svg
@Configuration @ComponentScan public class AppConfig { // 建立一个Bean, A是其余package中的 @Bean A createA() { return A.of("Z"); } }
Spring对标记为@Bean的方法只调用一次,所以返回的Bean仍然是单例。spa