重拾Springmvc之路---------《9》--------Spring的bean管理(基于注解的)注入属性

@Autowired  : 自动装配注入,是根据类名来找其对象的;

@Resource(name="")  : 需要加name 属性,name =“指定需要注解哪个对象”这里也就是表示:需要注入的对象注解表明的id的值;类似于配置文件执行是写的:

<bean id="" class="">
  <property name="" ref=""></property>
</bean>

demo直接看代码+注释:

@Service(value="serviceDemo")//创建对象 value 可以省略
public class ServiceDemo {

	//使用注解时候,不需要set方法;
	/*@Autowired  //自动注入,找的方式是根据类名对应的对象,
	private DaoDemo dao;*/
	@Resource(name="daoDemo")
	private DaoDemo dao;
	
	public void add(){
		System.out.println("service.......");
		dao.testDao();
	}
}
@Component(value="daoDemo")
public class DaoDemo {

	public void testDao(){
		System.out.println("你好,小谢");
	}
}
@Test
	public void test9(){
		ApplicationContext con=new ClassPathXmlApplicationContext("mapper/spring2.xml");
		ServiceDemo us=(ServiceDemo) con.getBean("serviceDemo");
		us.add();
		
	}




猜你喜欢

转载自blog.csdn.net/weixin_41524017/article/details/80512651