本文知识点来源于尚硅谷,感谢尚硅谷为广大学子提供的优质教育资源,感谢各位老师热情指导,本文仅作为学习笔记使用,记录学习心得,如有不适,请联系作者。
新建maven工程
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
被注入对象
public class Person {
private String name;
private Integer age;
private String sex;
public Person() {
super();
// TODO Auto-generated constructor stub
}
public Person(String name, Integer age, String sex) {
super();
this.name = name;
this.age = age;
this.sex = sex;
}
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;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", sex=" + sex + "]";
}
}
以前通过xml方式配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
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.tedu.bean.Person">
<property name="age" value= "18"></property>
<property name="name" value= "张三"></property>
<property name="sex" value= "男"></property>
</bean>
</beans>
测试类
public class MainTest_ConfigurationAndBean {
public static void main(String[] args) {
//以前通过xml配置的做法
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
Person person = (Person) applicationContext.getBean("person");
System.out.println(person);
}
}
输出:
Person [name=张三, age=18, sex=男]
使用@Configuration和@Bean注解注册
/**
* 配置类==配置文件xml
* @author Administrator
*
*/
@Configuration //告诉Spring这是一个配置类
public class MainConfig {
/**
* 给容器注册一个bean,类型为返回值类型,id默认是方法名
* 如果想指定id 可以写作@Bean("person2")
*
* @return
*/
//@Bean这样写的话bean id默认为方法名
@Bean("person2")//指定方法名
public Person person() {
return new Person("李四",18,"男");
}
}
public class MainTest_ConfigurationAndBean {
public static void main(String[] args) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
Person person = (Person) applicationContext.getBean(Person.class);
System.out.println(person);
String[] beanNames = applicationContext.getBeanNamesForType(Person.class);
for (String beanName : beanNames) {
System.out.println("beanName:" + beanName);
}
}
}
输出
Person [name=李四, age=18, sex=男]
beanName:person2