springboot实战电商项目mall4j (https://gitee.com/gz-yami/mall4j)
1. bean注册
我们有个Person类
public class Person {
private Integer age;
private String name;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person [age=" + age + ", name=" + name + "]";
}
}
1.1 传统bean注册
新建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.opgame.spring.Person">
<property name="age" value="18"/>
<property name="name" value="张三"/>
</bean>
</beans>
使用person对象进行测试
@Test
public void testBean() {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Person person = (Person)context.getBean("person");
System.out.println(person);
}
1.2 使用annotation代替xml注册
创建一个带有@Configuration
的java类,使用 @Bean
进行注册
@Configuration // 告诉spring这个是一个config类
public class BeansConfig {
// 给容器注册一个bean,类型为返回值类型,默认id为方法名,在bean注解中设置id
@Bean("person")
public Person person() {
Person person = new Person();
person.setAge(20);
person.setName("李四");
return person;
}
}
使用person对象进行测试
@Test
public void testBean