zoukankan      html  css  js  c++  java
  • 【spring】之xml和Annotation,Bean注入的方式

    基于xml形式Bean注入

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class PersonBean {
        private Integer id;
        private String name;
        private String address;
    }
    <bean class="com.luna.annotation.PersonBean" id="personBean">
            <property name="name" value="张三"/>
            <property name="address" value="上海"/>
            <property name="id" value="1"/>
        </bean>
     //基于xml完成数据Bean注入
        @Test
        public void test(){
            ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
            PersonBean personBean = (PersonBean) applicationContext.getBean("personBean");
            System.out.println(personBean.getAddress());
        }

    基于Annotation形式Bean注入

    @Configuration//告诉spring这是个配置类
    public class PersonBeanConfig {
    
        @Bean(value = "person")//默认情况下使用方法名作为属性名
        public PersonBean personBean(){
            return new PersonBean(1,"李四","北京");
        }
    
    
    }
    //基于纯注解完成数据注入
        @Test
        public void test(){
            ApplicationContext applicationContext = new AnnotationConfigApplicationContext(PersonBeanConfig.class);
            PersonBean personBean = applicationContext.getBean(PersonBean.class);//类型
            System.out.println(personBean.getAddress());
            PersonBean person = (PersonBean)applicationContext.getBean("person");//属性名
            System.out.println(person.getAddress());
            String[] names= applicationContext.getBeanNamesForType(PersonBean.class);//查看在容器中当前Bean的属性名
            for(String name:names){
                System.out.println(name);
            }
        }
  • 相关阅读:
    基于AngularJS的前端云组件最佳实践
    光裁员有什么用,商业变现才是王道
    迄今为止最完整的推送说明书
    个推技术实现原理介绍
    安卓推送——个推服务端api使用误区
    Gerrit代码Review入门实战
    iOS AFNetworking HTTPS 认证
    iOS开发零碎知识点
    Xcode 如何删除过期的Provisioning Profile文件
    一个section刷新 一个cell刷新
  • 原文地址:https://www.cnblogs.com/gyjx2016/p/8903709.html
Copyright © 2011-2022 走看看