spring框架学习四(ioc如何创建对象)

IOC

1.无参构造创建对象,

2.实体类
package com.yms.entity;

/**

  • @Author 杨明书
  • @PackageName: com.yms.entity
  • @ClassName: User
  • @Description:
  • @Date: 2021/12/29 14:11
    */
    public class User {
    private String name;

// public User(){
// System.out.println("user 的无参构造");
// }

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

public String getName() {
    return name;
}

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

public void  show(){
    System.out.println("姓名为:"+name);
}

}

3.配置文件

<bean id="user" class="com.yms.entity.User">
   <!--        无参赋值-->
    <constructor-arg name="name" value="钟无艳"></constructor-arg>
</bean>

4.测试类
import com.yms.entity.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**

  • @Author 杨明书
  • @PackageName: PACKAGE_NAME
  • @ClassName: MyTest
  • @Description:
  • @Date: 2021/12/29 14:13
    */
    public class MyTest {
    public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    User user = (User) context.getBean("user");
    user.show();

// User user = new User();

}

}

posted @ 2021-12-29 14:36  এএ᭄念卿এএ᭄  阅读(26)  评论(0编辑  收藏  举报