Employee.java:
package text.spring._05_instance.constructor;
/**
* Created by Administrator on 2019/9/2.
*/
public class Employee {
public Employee(){
System.out.println("构造函数的实例化方式");
}
}
App.java:
package text.spring._05_instance.constructor;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Created by Administrator on 2019/9/2.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class App {
@Autowired
private ApplicationContext context;
@Test
public void testOld(){
Employee em=new Employee();
System.out.println(em);
}
@Test
public void testSpring() throws Exception {
Employee employee = context.getBean(Employee.class);
System.out.println(employee);
}
}
App-context.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="employee" class="text.spring._05_instance.constructor.Employee">
</bean>
</beans>

本文通过Employee类演示了两种实例化方式:直接new和Spring容器管理。对比了传统实例化和Spring管理的区别,展示了如何在Spring中配置Bean并从容器获取实例。
3644

被折叠的 条评论
为什么被折叠?



