一、xml形式java
Person.java
package com.jackhu.bean; public class Person { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "com.jackhu.bean.Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } public Person(String name, int age) { super(); this.name = name; this.age = age; } public Person() { } }
beans.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 http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="person" class="com.jackhu.bean.Person"> <property name="name" value="zh"/> <property name="age" value="18"/> </bean> </beans>
MainTest.java
public class MainTest { public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml"); Person person = (Person) applicationContext.getBean("person"); System.out.println(person); } }
運行結果以下:spring
二、註解形式app
/** * 配置類==配置文件 * * @Configuration 告訴Spring這是一個配置類 * @Bean 給容器中註冊一個Bean,類型爲返回值類型,id默認是方法名做爲id */ @Configuration public class MainConfig { @Bean("person") public Person person2() { return new Person("JACK", 18); } }
public class MainTest { public static void main(String[] args) { // 一、xml形式 // ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml"); // Person person = (Person) applicationContext.getBean("person"); // System.out.println(person); // 二、註解形式 ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class); Person person = applicationContext.getBean(Person.class); System.out.println(person); String[] namesForType = applicationContext.getBeanNamesForType(Person.class); for (String name : namesForType) { System.out.println(name); } } }
三、包掃描@ComponentScanide
@Configuration @ComponentScan(value = "com.jackhu") public class MainConfig { @Bean("person") public Person person2() { return new Person("JACK", 18); } }
測試類測試
public class IOCTest { @Test public void main() { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class); // 容器中全部bean名稱 String[] names = applicationContext.getBeanDefinitionNames(); for (String name : names) { System.out.println(name); } } }
增長組件標記this
輸出結果:3d
源碼解析:xml
@Configuration @ComponentScan(value = "com.jackhu", excludeFilters = { @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {Controller.class, Service.class}) // excludeFilters排除 Controller和Service註解不加進來 }) public class MainConfig { @Bean("person") public Person person2() { return new Person("JACK", 18); } }
includeFilters同理