Spring中通过注解配置bean(2)--@Autowired
1、UserRepository接口和对应的实现类
package com.at.beans.annotation.repository;
public interface UserRepository {
void save();
}
package com.at.beans.annotation.repository;
import org.springframework.stereotype.Repository;
@Repository("userRepository")
public class UserRepositoryImpl implements UserRepository{
public void save() {
System.out.println("UserRepository Save......");
}
}
package com.at.beans.annotation.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.at.beans.annotation.repository.UserRepository;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public void add(){
System.out.println("UserService add......");
userRepository.save();
}
}
package com.at.beans.annotation.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.at.beans.annotation.service.UserService;
@Controller
public class UserController {
@Autowired
private UserService userService;
public void execute(){
System.out.println("UserController execute......");
userService.add();
}
}
UserController userController = (UserController) ctx.getBean("userController");
System.out.println(userController);
userController.execute();
六月 04, 2017 6:12:24 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@6be3f34c: startup date [Sun Jun 04 18:12:24 CST 2017]; root of context hierarchy
六月 04, 2017 6:12:24 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans-annotation.xml]
com.at.beans.annotation.controller.UserController@2e909348
UserController execute......
UserService add......
UserRepository Save......
1、@Autowired的原理
其实在启动spring IoC容器的时候,容器自动装载了一个AutowiredAnnotationBeanPostProcessor后置处理器,当容器扫描到@Autowied、@Resource或@Inject时,就会在IoC容器自动查找需要的bean,并装配给该对象的属性
By luoyepiaoxue2014
微博地址:http://weibo.com/luoyepiaoxue2014 点击打开链接