Spring依赖注入 c命名空间注入 p命名空间注入

Spring的简单介绍

  1. Spring是一个开放源代码的设计层面框架,他解决的是业务逻辑层和其他各层的松耦合问题,因此它将面向接口的编程思想贯穿整个系统应用。Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson创建。简单来说,Spring是一个分层的JavaSE/EE full-stack(一站式) 轻量级开源框架,Spring 框架是一个分层架构,由 7 个定义良好的模块组成。Spring模块构建在核心容器之上,核心容器定义了创建、配置和管理 bean 的方式。
    在这里插入图片描述
  2. Spring框架即以 interface21 框架为基础。
  3. Spring框架:
    3.1 轻量级
    3.2 面向切面
    3.3 控制翻转 (IOC)【inversion of Control】:类的实例由容器的ClassPathXmlApplicationContext创建。
    3.4 Spring 包含并管理对象的创建和生命周期,在意义上,它是一个容器。
    3.5 框架:在Spring中,应用对象被声明式地组合,典型地是在一个XML文件里。Spring也提供了很多基础功能(事务管理、持久化框架集成等等),将应用逻辑的开发留给了你。
  4. Spring 优点:
    4.1.低侵入式设计,代码污染极低。
    4.2.独立于各种应用服务器,基于Spring框架的应用,可以真正实现Write Once,Run Anywhere的承诺。
    4.3.Spring的DI机制降低了业务对象替换的复杂性,提高了组件之间的解耦。
    4.4.Spring的AOP支持允许将一些通用任务如安全、事务、日志等进行集中式管理,从而提供了更好的复用。
    4.5.Spring的ORM和DAO提供了与第三方持久层框架的良好整合,并简化了底层的数据库访问。
    4.6.Spring并不强制应用完全依赖于Spring,开发者可自由选用Spring框架的部分或全部。

Spring的简单使用

  1. 首先在maven中找到Spring的依赖:https://mvnrepository.com/artifact/org.springframework/spring-webmvc
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.9.RELEASE</version>
        </dependency>
  1. 实体类
package com.baidu.pojo;

public class Hello {
    private int age;
    private String sex;
    private String name;

    public Hello(String name) {
        System.out.println("有参构造只有name的");
        this.name = name;
    }

    public Hello(int age, String sex, String name) {
        System.out.println("有参构造全部内容");
        this.age = age;
        this.sex = sex;
        this.name = name;
    }

    public Hello(){
        System.out.println("无参构造");
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
        System.out.println("通过set方法设置name");
    }

    @Override
    public String toString() {
        return "Hello{" +
                "age=" + age +
                ", sex='" + sex + '\'' +
                ", name='" + name + '\'' +
                '}';
    }
}

  1. 创建对应的bean.xml文件
<?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:c="http://www.springframework.org/schema/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">
	<!--通过无参构造和set方法创建对象-->
    <bean id="hello1" class="com.baidu.pojo.Hello">
        <property name="name" value="Spring"></property>
    </bean>
	<!--通过有参构造创建对象,最后通过set重新设置name属性-->
    <bean id="hello2" class="com.baidu.pojo.Hello">
        <constructor-arg index="0" value="18"/>
        <constructor-arg index="2" value="girl"/>
        <constructor-arg index="1" value="郝一凡1"/>
        <property name="name" value="郝一凡6"/>
    </bean>
	<!--通过有参构造创建对象-->
    <bean id="hello3" class="com.baidu.pojo.Hello">
        <constructor-arg value="18"/>
        <constructor-arg value="girl2"/>
        <constructor-arg value="郝一凡3"/>
    </bean>
    <!--通过有参构造创建对象-->
    <bean id="hello4" class="com.baidu.pojo.Hello">
        <constructor-arg name="age" value="19"/>
        <constructor-arg name="name" value="郝一凡4"/>
        <constructor-arg name="sex" value="gril4"/>
    </bean>
	<!--通过参数的数据类型创建对象-->
    <bean id="hello5" class="com.baidu.pojo.Hello">
        <constructor-arg type="java.lang.String" value="郝一凡5"/>
    </bean>
    <!--给创建的对象起别名-->
    <alias name="hello5" alias="hellohello"/>
</beans>
  1. 测试类
package com.baidu.pojo;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class HelloTest {
    @Test
    public void test(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        Hello hello1 = (Hello) context.getBean("hello1");
        System.out.println(hello1.toString());
    }

    @Test
    public void test1(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        Hello hello1 = (Hello) context.getBean("hello2");
        System.out.println(hello1.toString());
    }

    @Test
    public void test3(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        Hello hello1 = (Hello) context.getBean("hello3");
        System.out.println(hello1.toString());
    }

    @Test
    public void test4(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        Hello hello1 = (Hello) context.getBean("hello4");
        System.out.println(hello1.toString());
    }

    @Test
    public void test5(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        Hello hello1 = (Hello) context.getBean("hellohello");
        System.out.println(hello1.toString());
    }
}

我这里测试的是test5
在这里插入图片描述
6. bean.xml 中的import标签

<!--
    classpath*:会在所有文件中去找,效率低,不建议使用
    classpath:在此项目中找寻,效率高,建议使用
    file:需要找到文件的绝对路径,不推荐使用
    http:需要找到文件的网络路径,不推荐使用
    -->
    <import resource="classpath*:"/>
    <import resource="classpath:"/>
    <import resource="file:"/>
    <import resource="http:"/>

依赖注入DI

  1. 创建实体类
package com.baidu.pojo;

import java.util.*;

public class User {
    private String name;
    private int age;
    private Address address;
    private String[] hobbys;
    private Set<String> books;
    private List<String> names;
    private Map<String,String> users;
    private Properties properties;
    private User girlFriend;

    public User() {
    }

    public User(String name, int age, Address address, String[] hobbys, Set<String> books, List<String> names, Map<String, String> users, Properties properties, User girlFriend) {
        this.name = name;
        this.age = age;
        this.address = address;
        this.hobbys = hobbys;
        this.books = books;
        this.names = names;
        this.users = users;
        this.properties = properties;
        this.girlFriend = girlFriend;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", address=" + address +
                ", hobbys=" + Arrays.toString(hobbys) +
                ", books=" + books +
                ", names=" + names +
                ", users=" + users +
                ", properties=" + properties +
                ", girlFriend=" + girlFriend +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public String[] getHobbys() {
        return hobbys;
    }

    public void setHobbys(String[] hobbys) {
        this.hobbys = hobbys;
    }

    public Set<String> getBooks() {
        return books;
    }

    public void setBooks(Set<String> books) {
        this.books = books;
    }

    public List<String> getNames() {
        return names;
    }

    public void setNames(List<String> names) {
        this.names = names;
    }

    public Map<String, String> getUsers() {
        return users;
    }

    public void setUsers(Map<String, String> users) {
        this.users = users;
    }

    public Properties getProperties() {
        return properties;
    }

    public void setProperties(Properties properties) {
        this.properties = properties;
    }

    public User getGirlFriend() {
        return girlFriend;
    }

    public void setGirlFriend(User girlFriend) {
        this.girlFriend = girlFriend;
    }
}

package com.baidu.pojo;

public class Address {
    private String name;

    public Address() {
    }

    public Address(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Address{" +
                "name='" + name + '\'' +
                '}';
    }
}

  1. 配置对应的bean.xml文件
<bean id="user" class="com.baidu.pojo.User">
        <!--普通注入-->
        <property name="name" value="郝一凡"/>
        <!--引入注入-->
        <property name="address" ref="address"/>

        <property name="age" value="18"/>
        <!--set注入-->
        <property name="books">
            <set>
                <value>西游记</value>
                <value>三国演义</value>
                <value>红楼梦</value>
                <value>水浒传</value>
            </set>
        </property>
        <!--空值注入-->
        <property name="girlFriend">
            <null/>
        </property>
        <!--数组注入-->
        <property name="hobbys">
            <array>
                <value>电影</value>
                <value>音乐</value>
                <value>游戏</value>
            </array>
        </property>
        <!--list注入-->
        <property name="names">
            <list>
                <value>王者荣耀</value>
                <value>刺激战场</value>
                <value>绝地求生</value>
            </list>
        </property>
        <!--map注入-->
        <property name="users">
            <map>
                <entry key="name" value="郝一龙"/>
                <entry key="age" value="14"/>
                <entry key="sex" value="boy"/>
            </map>
        </property>
        <!--properties注入-->
        <property name="properties">
            <props>
                <prop key="时间">2019-07-26</prop>
            </props>
        </property>
    </bean>

c命名空间注入和p命名空间注入

这个的使用要在bean.xml文件的头目录里面加上两行语句
	   xmlns:p="http://www.springframework.org/schema/p" 
       xmlns:c="http://www.springframework.org/schema/c"
<bean id="address1" class="com.baidu.pojo.Address" p:name="陕西省"/>
<bean id="address2" class="com.baidu.pojo.Address" c:name="宝鸡市"/>

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
接入Apollo实现Spring依赖注入的Bean动态刷新,需要以下步骤: 1. 引入Apollo的依赖 在Maven或Gradle中添加Apollo的依赖: Maven: ```xml <dependency> <groupId>com.ctrip.framework.apollo</groupId> <artifactId>apollo-client</artifactId> <version>${apollo.version}</version> </dependency> ``` Gradle: ``` compile 'com.ctrip.framework.apollo:apollo-client:${apollo.version}' ``` 其中`${apollo.version}`是Apollo的版本号。 2. 实现ApolloConfigChangeListener接口 ```java import com.ctrip.framework.apollo.model.ConfigChangeEvent; import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener; import org.springframework.stereotype.Component; @Component public class MyApolloConfigChangeListener { @ApolloConfigChangeListener private void onChange(ConfigChangeEvent changeEvent) { // 配置变化时的回调方法 } } ``` 3. 实现BeanPostProcessor接口 ```java import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.stereotype.Component; @Component public class MyBeanPostProcessor implements BeanPostProcessor { private final ConfigurableListableBeanFactory beanFactory; public MyBeanPostProcessor(ConfigurableListableBeanFactory beanFactory) { this.beanFactory = beanFactory; } @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof MyConfigurableBean) { MyConfigurableBean myConfigurableBean = (MyConfigurableBean) bean; String configValue = myConfigurableBean.getConfigValue(); // 从Apollo配置中心获取配置 myConfigurableBean.setConfigValue(configValue); } return bean; } @ApolloConfigChangeListener private void onChange(ConfigChangeEvent changeEvent) { if (changeEvent.isChanged("my.config.key")) { beanFactory.destroySingleton("myConfigurableBean"); // 销毁旧的Bean实例 } } } ``` 在这个例子中,我们实现了一个`MyConfigurableBean`,这个Bean的属性`configValue`是从Apollo配置中心获取的。当Apollo配置中心的配置发生变化时,我们会销毁旧的Bean实例,并重新创建新的Bean实例。 4. 配置Apollo 在`application.properties`或`application.yml`中配置Apollo相关参数: ```yaml apollo: meta: # Apollo Portal的地址 http://localhost:8080 # Apollo AppId appId: myAppId # Apollo配置中心的命名空间 namespace: application ``` 至此,我们就成功地接入了Apollo,实现了Spring依赖注入的Bean动态刷新。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值