说明:使用@Autowired虽然不需要再配置相关参数,但是还是要在配置文件中配置bean,今天我们完全使用注解的方法来实现一下
1.使用注解来在上下文装载bean:(这里不再需要setter方法一样可以运行)
1.@Component(不推荐使用)、@Repository、@Service、@Controller 只需要在对应的类上加上一个@Component注解,就将该类定义为一个Bean了。 2.使用@Component注解定义的Bean,默认的名称(id)是小写开头的非限定类名。如这里定义的Bean名称就是 userDaoImpl。你也可以指定Bean的名称: @Component("userDao") 3.@Component是所有受Spring管理组件的通用形式,Spring还提供了更加细化的注解形式:@Repository、 @Service、@Controller,它们分别对应存储层Bean,业务层Bean,和展示层Bean。 @Service public class AutoWiringService { @Autowired private AutoWiringDAO autoWiringDAO; public void serviceSave(String meString) { autoWiringDAO.save(meString); } } 使用context:component-scan 标签让Bean定义注解工作起来 : <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <context:component-scan base-package="com.wuyonghu" /> </beans>3.测试代码:
@Test public void testHello5() { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); System.out.println(context); AutoWiringService bean = (AutoWiringService) context.getBean("autoWiringService"); bean.serviceSave("吳永鬍"); }