Spring的DI注入方式:xml注入

/* * @Autowired private IStudentService studentService; / @Test public void myTest2() { String resoure = “applicationContext.xml”; ApplicationContext applicationContext = new ClassPathXmlApplicationContext(resoure); // property:设值注入 / * Student student=(Student) applicationContext.getBean(“StudentBean”); * System.out.println(student); //Student [studentId=null, * classId=15,studentname=张三, gender=男] * 加上School实体类 //Student [studentId=null,classId=15, studentname=张三, gender=男, school=School [school=广东大学]] / // constructor-arg:构造注入:不需要set,所有属性都要赋值 / * Student student=(Student)applicationContext.getBean(“StudentBean”); * System.out.println(student); * Student [studentId=16, classId=17,studentname=李四, gender=王五] * 加上School实体类 * //Student [studentId=16, classId=17,studentname=李四, gender=王五, school=School[school=广东大学]] / // 命名空间注入1,p:xmlns:p="http://www.springframework.org/schema/p // 命名空间注入2,c:xmlns:p="http://www.springframework.org/schema/c // 二者用法一致 / * Student student=(Student)applicationContext.getBean(“StudentBean”); * System.out.println(student); //Student [studentId=null, classId=18, * //studentname=鬼六, gender=null, school=School [school=广东大学]] / //集合注入:name命名与实体类一致 / * Some some=(Some) applicationContext.getBean(“someBean”); * System.out.println(some); * //Some [schools=[School [school=广东大学1], School[school=广东大学2]], myList=[张三, 李四], mySet=[广东, 湖南], myMap={今天=还行, 明天=美好},myProps={您好=晴天, 你好=雨天}] / //域属性自动注入:autowire //byname,将域属性名做为id到容器中查找相同名称的bean进行自动注入:name要求实体类名称一致 //bytype,将域属性类型做为id到容器中查找相同名称的bean进行自动注入:要求相同类型的bean不能多于一个(包含以及其字类) / * Student student=(Student)applicationContext.getBean(“StudentBean”); * System.out.println(student); //Student [studentId=null, classId=null, * studentname=张三, gender=男, school=School [school=广东大学]] / //spring el表达式简称:SPEL表达式注入:格式:#{Student.gender} //感觉与el表达式差不多 //匿名bean:没有name和id的bean //内部bean注入: / * Student student=(Student)applicationContext.getBean(“StudentBean”); * System.out.println(student); //Student [studentId=null, classId=null, * studentname=张三, gender=男, school=School [school=广东大学]] / //使用同类抽象bean注入:parent=“父” / * Student student1=(Student)applicationContext.getBean(“StudentBean1”); Student * student2=(Student)applicationContext.getBean(“StudentBean2”); * System.out.println(student1); System.out.println(student2); //Student * [studentId=null, classId=1, studentname=张三, gender=男, school=null] //Student * [studentId=null, classId=1, studentname=李四, gender=男, school=null] */ //使用异类抽象bean注入:原理一致,提出相同属性赋值即可

Applicationcontext配置:
加上School实体类 张三 李四 广东 湖南 雨天 晴天 内部匿名bean

猜你喜欢

转载自blog.csdn.net/weixin_44543131/article/details/113172946
今日推荐