?
<beans> <bean id="orderService" class="com.acme.OrderService"/> <constructor-arg ref="orderRepository"/> </bean> <bean id="orderRepository" class="com.acme.OrderRepository"/> <constructor-arg ref="dataSource"/> </bean> </beans>
?
?
ApplicationContext ctx = new ClassPathXmlApplicationContext("application-config.xml"); OrderService orderService = (OrderService) ctx.getBean("orderService");
?
@Configuration public class ApplicationConfig { public @Bean OrderService orderService() { return new OrderService(orderRepository()); } public @Bean OrderRepository orderRepository() { return new OrderRepository(dataSource()); } public @Bean DataSource dataSource() { // instantiate and return an new DataSource … } }
?
JavaConfigApplicationContext ctx = new JavaConfigApplicationContext(ApplicationConfig.class); OrderService orderService = ctx.getBean(OrderService.class);
?
?
?
@Scope("prototype") public class PrintTask2 implements Runnable { String name; public void setName(String name) { this.name = name; } @Override public void run(){ System.out.println(name + " is running."); try{ Thread.sleep(5000); }catch(InterruptedException e){ e.printStackTrace(); } System.out.println(name + " is running again."); } }
?
?
如果action或Service中不@Scope("prototype"),有可能报找不到xxxaction或Service的错误!写上这个就表示每次请求都重新创建一个action或Service,与SINGALON对应,俗称“多例”。
?
@Component @Scope("prototype") public class PrintTask2 implements Runnable { String name; public void setName(String name) { this.name = name; } @Override public void run(){ System.out.println(name + " is running."); try{ Thread.sleep(5000); }catch(InterruptedException e){ e.printStackTrace(); } System.out.println(name + " is running again."); } }
把普通pojo实例化到spring容器中,相当于配置文件中的<bean id="" class=""/>
?
?
@Repository public class DaoImpl implements IDao{ }
?应用于Dao层,把该类注册到Spring容器中
?
?
?
@Service public class ServiceImpl implements IService { @Autowired private IDao iDao; }
?应用于Service层,把该类注册到Spring容器中
?
?
?
@Controller public class TestController { @Autowired private IService iService; }
??应用于Action层,把该类注册到Spring容器中
?
@Autowired , @Qualifier("XXX")
?
@Service public class TestServiceImpl { @Autowired @Qualifier("iTestDao2") private ITestDao iTestDao; }
在ITestDao接口标上@Autowired和@Qualifier注释使得ITestDao接口存在两个实现类的时候必须指定其中一个来注入,使用实现类首字母小写的字符串("iTestDao2")来注入。否则可以省略,只写@Autowired??
?
原文:http://zliguo.iteye.com/blog/2250213