1.Spring装配Bean的两种方式
1.使用XML装配Bean
1、引入约束
2、创建应用类
package com.ma.spring.demo01;
public class User {
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 "User{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
}
3、配置文件
<!--默认使用无参的构造器-->
<bean id = "user" class = "com.ma.spring.demo01.User" scope="singleton" >
<property name="age" value="20"></property>
<property name="name" value="Young"></property>
</bean>
4、测试类
package com.ma.spring.demo01;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.beans.IntrospectionException;
import java.lang.reflect.Method;
public class UserTest {
@Test
public void test01() {
//1、创建Spring的工厂对象(BeanFactory ApplicationContext)
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
//2、使用applicationContext.xml内部配置的bean来创建对象
User user= (User) applicationContext.getBean("user");
System.out.println(user);
//applicationContext.close();
}
@Test
public void test02() throws ClassNotFoundException, IntrospectionException, IllegalAccessException, InstantiationException {
Class clazz = Class.forName("com.ma.spring.demo01.User");
//PropertyDescriptor propertyDescriptor = new PropertyDescriptor("name",clazz);
//System.out.println(propertyDescriptor.getWriteMethod().getName());
Object obj = clazz.newInstance();
for(Method method : clazz.getMethods()){
if(method.getName().startsWith("set")){
System.out.println(method.getName());
}
}
}
}
5、效果
2.使用注解装配Bean
Spring2.5引入使用注解去定义Bean
@Component 描述Spring框架中的Bean
Spring框架提供了与@Component注解等效的三个注解:
@Repository用于对DAO实现类进行标注
@Service用于对Service实现类进行标注
@Controller用于对Controller实现类进行标注
1、引入约束
2、创建应用类
package com.ma.spring.demo02;
import org.springframework.stereotype.Component;
@Component("userService")
public class UserService {
public void addUser(){
System.out.println("UserService......");
}
}
3、配置注解扫描
4、测试类
package com.ma.spring.demo02;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class UserServiceTest {
@Test
public void testAddUser(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = (UserService) applicationContext.getBean("userService");
userService.addUser();
}
}
5、效果