一、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同理