Spring命名空间注入

p命名空间注入

  1. 需要有set方法
  2. 需要添加约束
xmlns:p="http://www.springframework.org/schema/p"
  1. 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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
        
        <bean id="people" class="cn.lee.bean.People" p:name="鲁迅" p:age="65">        	
        </bean> 
</beans>

c命名空间注入

  1. 需要有构造方法
  2. 需要添加约束
xmlns:c="http://www.springframework.org/schema/c"
  1. 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:c="http://www.springframework.org/schema/c"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
        
        <bean id="people" class="cn.lee.bean.People" c:name="鲁迅" c:age="65"></bean> 
</beans>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring 中,构造方法注入是一种依赖注入的方式,它通过构造方法来实现对依赖对象的注入。以下是如何在 Spring 中进行构造方法注入的步骤: 1. 创建需要被注入的依赖对象的类,并在该类的构造方法上添加 `@Autowired` 注解。 ```java public class Dependency { // 使用@Autowired 注解进行构造方法注入 @Autowired public Dependency() { // 构造方法逻辑 } } ``` 2. 在需要使用该依赖对象的类中,声明该依赖对象的成员变量,并在该成员变量上添加 `@Autowired` 注解。 ```java public class MyClass { // 使用@Autowired 注解进行构造方法注入 @Autowired private Dependency dependency; } ``` 3. 在 Spring 的配置文件(例如 applicationContext.xml)中,配置依赖对象和需要使用该对象的类。 ```xml <!-- 配置依赖对象 --> <bean id="dependency" class="com.example.Dependency" /> <!-- 配置需要使用该对象的类 --> <bean id="myClass" class="com.example.MyClass" /> ``` 这样,当 Spring 容器启动时,会自动识别 `@Autowired` 注解,并在初始化对象时自动将依赖对象注入到需要使用它的地方。注意,需要保证配置文件中已经正确引入了 Spring命名空间和依赖注入的约束。 除了使用 `@Autowired` 注解进行构造方法注入,还可以使用 `@Inject` 注解或者通过 XML 配置文件的方式实现构造方法注入。具体选择哪种方式取决于个人偏好和项目需求。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值