SpringIoc容器创建Bean
实体类
public class User {
private Integer id;
private String name;
private String pwd;
public User() { }
public User(Integer id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
spring的xml配置文件配置bean
<!--方法设值-->
<bean id="getUser" class="edu.gdkm.po.User">
<property name="id" value="12"></property>
<property name="name" value="梁俊"></property>
<property name="pwd" value="18602003024"></property>
</bean>
<!--构造器设值-->
<bean id="getConUser" class="edu.gdkm.po.User">
<constructor-arg index="0" name="id" value="321"></constructor-arg>
<constructor-arg index="1" name="name" value="aagahha"></constructor-arg>
<constructor-arg index="2" name="pwd" value="13169126919"></constructor-arg>
</bean>
测试类获取bean
public static void testUserDao(){
public static void main(String[] args) {
ApplicationContext act = new ClassPathXmlApplicationContext("applicationContext.xml");
User getConUser = act.getBean("getConUser", User.class);
System.out.println(getConUser );
}
spring注解注入bean
创建UserController
@Controller
public class UserController {
@Resource(name = "userService")
private UserService userService;
public void test() {
userService.test();
System.out.println("UserController被创建");
}
}
UserDao接口
public interface UserDao {
void test();
}
UserDao接口实现类
@Repository(value = "userDao")
public class UserDaoImpl implements UserDao {
@Override
public void test() {
System.out.println("userDao被执行");
}
}
UserService接口
public interface UserService {
void test();
}
UserService接口实现类
@Service(value = "userService")
public class UserServiceImpl implements UserService {
@Resource(name = "userDao")
private UserDao userDao;
@Override
public void test() {
userDao.test();
System.out.println("userService被创建");
}
}
测试类测试注解
public class AnnotationAssembleTest {
public static void main(String[] args) {
ApplicationContext act = new ClassPathXmlApplicationContext("applicationContext.xml");
//测试注解
UserController userController = act.getBean(UserController.class);
userController.test();
}
}