目录
1、xml方式
1.1 beans.xml
<bean id="person" class="com.atguigu.bean.Person" > <property name="age" value="18"></property> <property name="name" value="zhangsan"></property> </bean>
1.2 测试类
package com.atguigu; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.atguigu.bean.Person; public class MainTest { @SuppressWarnings("resource") public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml"); Person bean = (Person) applicationContext.getBean("person"); System.out.println(bean); } }
2、注解方式
2.1 MainConfig.class
package com.atguigu.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.atguigu.bean.Person; //配置类==配置文件 @Configuration //告诉Spring这是一个配置类 public class MainConfig { //给容器中注册一个Bean;类型为返回值的类型,id默认是用方法名作为id @Bean("person") public Person person01(){ return new Person("lisi", 20); } }
2.2 测试类
package com.atguigu; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import com.atguigu.bean.Person; import com.atguigu.config.MainConfig; public class MainTest { @SuppressWarnings("resource") public static void main(String[] args) { ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class); Person bean = applicationContext.getBean(Person.class); System.out.println(bean); String[] namesForType = applicationContext.getBeanNamesForType(Person.class); for (String name : namesForType) { System.out.println(name); } } }