标签:
接着昨天的内容,下面开始IOC基于注解装配相关的内容
在 classpath 中扫描组件
<context:component-scan>
1 package per.zww.spring.beans.annotation; 2 3 import org.springframework.stereotype.Component; 4 5 @Component 6 public class TestObject { 7 public void test(){ 8 System.out.println("testObject..."); 9 } 10 }
1 package per.zww.spring.beans.annotation.respository; 2 3 import org.springframework.stereotype.Repository; 4 5 @Repository("userRepository") 6 public class UserRepository { 7 public void repository() { 8 System.out.println("repository..."); 9 } 10 }
xml:
<context:component-scan base-package="per.zww.spring.beans.annotation.*"></context:component-scan>
测试:
package per.zww.spring.beans.annotation; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { ApplicationContext applicationContext=new ClassPathXmlApplicationContext("annotation.xml"); TestObject testObject=(TestObject) applicationContext.getBean("testObject"); testObject.test(); UserRepository userRepository=applicationContext.getBean(UserRepository.class); userRepository.repository(); } }
另外我们可以过滤掉一些类:
package per.zww.spring.beans.annotation.service; public interface UserService { void service(); }
package per.zww.spring.beans.annotation.service; import org.springframework.stereotype.Service; @Service("userService") public class UserServiceImp implements UserService{ @Override public void service() { System.out.println("service..."); } }
package per.zww.spring.beans.annotation.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import per.zww.spring.beans.annotation.service.UserService;
@Controller
public class UserController {
@Autowired
@Qualifier("userService") //可以用Qualifier来精确匹配
public UserService userService;
public void controller() {
System.out.println("controller...");
userService.service();
}
}
测试:
package per.zww.spring.beans.annotation; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import per.zww.spring.beans.annotation.controller.UserController; import per.zww.spring.beans.annotation.service.UserService; public class Main { public static void main(String[] args) { UserController userController=(UserController) applicationContext.getBean("userController"); userController.controller(); } }
标签:
原文地址:http://www.cnblogs.com/zhaoww/p/5104822.html