Skip to main content

Bean方式

通过默认构造方法实例化Bean

public class Bean {
public Bean()
{
System.out.println("Bean+++++++++++++++");
}
}
  • XML
<bean id="bean" class="cn.asdasd.java.ioc.Bean"></bean>
  • 测试代码
import cn.asdasd.java.ioc.Bean;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class IocTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Bean bean = context.getBean("bean", Bean.class);
System.out.println("bean === " +bean);
}
}

通过静态工厂方法实例化Bean

public class Bean {
public Bean()
{
System.out.println("Bean+++++++++++++++");
}
}
public class Bean2 {
public static Bean getBean2(){
return new Bean();
}
}

  • XML
<bean id="bean2" class="cn.asdasd.java.ioc.Bean2" factory-method="getBean2" ></bean>
  • 测试代码
import cn.asdasd.java.ioc.Bean;
import cn.asdasd.java.ioc.Bean2;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class IocTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Bean dd2 = Bean2.getBean2();
System.out.println("bean =++++++++++++++++++++++++++ " + dd2);
}
}

通过实例工厂方法实例化Bean

public class Bean {
public Bean()
{
System.out.println("Bean+++++++++++++++");
}
}
public class Bean3 {
public Bean1 getBean3(){
return new Bean1();
}
}
  • XML
    <bean id="bean1" class="cn.asdasd.java.ioc.Bean3"></bean>
<bean id="bean3" class="cn.asdasd.java.ioc.Bean" factory-bean="bean1"
factory-method="getBean3"></bean>
  • 测试代码
import cn.asdasd.java.ioc.Bean;
import cn.asdasd.java.ioc.Bean2;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class IocTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Bean3 b3 = new Bean3();
Bean bean = b3.getBean3();
}
}

Bean的别名

  • XML
<bean id="bean" class="cn.asdasd.java.ioc.Bean" name="ddd"></bean>
  • 测试代码
import cn.asdasd.java.ioc.Bean;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class IocTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Bean bean = context.getBean("ddd", Bean.class);
System.out.println("bean === " +bean);
}
}