spring容器中注册组件的两种方式:java
1.一、编写bean类spring
package com.jcon.entity; /** * @author Jcon * @version V1.0 * @Description: (用户实体类) * @date 2019年01月28日 */ public class Person { private String name; private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
1.二、使用xml文件配置bean注入到spring容器app
<?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.jcon.entity.Person"> <property name="age" value="20"/> <property name="name" value="张三"/> </bean> </beans>
1.三、经过ClassPathXmlApplicationContext类获取beanide
// 传统xml方式注入bean并从容器中获取 @Test public void xmlGetBean(){ ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml"); Person person = (Person) applicationContext.getBean("person"); System.out.println(person); }
2.一、编写bean类this
package com.jcon.entity; /** * @author Jcon * @version V1.0 * @Description: (用户实体类) * @date 2019年01月28日 */ public class Person { private String name; private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
2.二、编写bean配置类,使用注解注入beanspa
package com.jcon.entity; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @author Jcon * @version V1.0 * @Description: (配置类) * @date 2019年01月28日 */ @Configuration public class Config { @Bean("person") public Person getPerson(){ Person person = new Person(); person.setAge(18); person.setName("李四"); return person; } }
2.三、经过AnnotationConfigApplicationContext获取bean对象3d
// 注解方式注入bean并从容器中获取 @Test public void annotationGetBean(){ AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Config.class); Person person = (Person) applicationContext.getBean("person"); // 对应bean名字为@bean方法的方法名,也能够使用@bean("name")指定bean名字 System.out.println(person); }
总结code