spring

2021-06-17 22:03

阅读:377

标签:str   set   play   nim   ann   配置   port   highlight   this   

1、bean配置的三种方式

(1)使用@Bean注解

package mybean;

public class MyBean {
    private String name = "大法师";

    public String getName() {
        return name;
    }

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

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MySpring {
    @Bean
    public MyBean make() {
        return new MyBean();
    }
}  
 public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        MyBean myBean = (MyBean) context.getBean("make");
        System.out.println(myBean.getName());//大法师
   }

applicationContext.xml中配置

(2)使用XML配置bean

package mybean;

public class Animal {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
 public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
       Animal animal = (Animal)context.getBean("animal");
        System.out.println(animal.getName());//小猫
   }
applicationContext.xml中配置
    

(3)使用注解

package mybean;

import org.springframework.stereotype.Component;

@Component
public class MyHome {
    public void play() {
        System.out.println("这是我家");
    }

    public void run() {
        System.out.println("这不是我家");
    }
}
public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
       MyHome myHome = (MyHome)context.getBean("myHome");
        myHome.play();//这是我家
   }
applicationContext.xml中配置

  

 

 

spring

标签:str   set   play   nim   ann   配置   port   highlight   this   

原文地址:https://www.cnblogs.com/yiyibinbin/p/9718941.html


评论


亲,登录后才可以留言!