您的位置:首页 > 博客中心 > 互联网 >

拓展方式注入

时间:2022-05-11 12:22

拓展方式注入

  • 使用p命名空间和c命名空间进行注入

    实体类

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private String name;
    private int age;
}

p命名空间注入

p命名空间注入,可以直接注入属性值:相当于property标签的属性注入

要在配置文件导入xml约束

xmlns:p="http://www.springframework.org/schema/p"

配置文件



    
    

测试:

@Test
public void UserTset(){
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("user.xml");
    User user = (User) applicationContext.getBean("user");
    System.out.println(user);
}

//User(name=张三, age=18)

c命名空间注入

  • c命名空间注入,构造器注入:相当于constructor-arg标签注入

要在配置文件导入xml约束

xmlns:c="http://www.springframework.org/schema/c"

配置文件



    
    

测试:

@Test
public void UserTset(){
    ApplicationContext applicationContext = new ClassPathXmlApplicationContext("user.xml");
    User user = (User) applicationContext.getBean("user2");
    System.out.println(user);
}

注意点

p命名空间和c命名空间不能直接使用,需要导入xml约束!

 xmlns:p="http://www.springframework.org/schema/p" 
 xmlns:c="http://www.springframework.org/schema/c"

本类排行

今日推荐

热门手游