首先通过一个简单的程序学习Spring在程序中的运用。
定义一个接口:
package com.spring.interfacebean;
public interface PersonBean
{
void show();
}
package com.spring.implbean;
import com.spring.interfacebean.PersonBean;
public class UserBean implements PersonBean
{
public void show()
{
System.out.println("Hello world");
}
}
package com.spring.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.spring.interfacebean.PersonBean;
public class TestClass
{
@Test
public void testMethod() throws Exception
{
//读取配置文件
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
//获取UserBean的实例
PersonBean bean=(PersonBean)ctx.getBean("userBean");
//调用方法
bean.show();
}
}
1,使用类构造器实例化对象
2,使用静态工厂的方法实例化对象
3,使用实例工厂的方法实例化对象
三种实例化对象的代码如下所示:
package com.spring.factory;
import com.szy.spring.implbean.UserBean;
import com.szy.spring.interfacebean.PersonBean;
public class BeanFactory
{
//使用静态工厂的方法实例化使用
public static PersonBean UserBeanService()
{
return new UserBean();
}
public PersonBean getUserBeanService()
{
return new UserBean();
}
}
在Spring中的注解:
@Service :用于标注配置业务层(service层)组件
@Cotroller:用于标注配置控制层组件
@Reponsitory:用于标注一般的DAO层Bean对象
@Component:泛指组件,对一般不好归入以上三种中的一种是使用
Spring的自动装配:
自动装配是指不用显示的手动配置java Bean之间的依赖关系,而是让Spring依据某种规则自动将合适的对象注入目标对象中。Spring中常用@Autowire和@Resource进行自动装配。
@Autowire:默认是按照对象的数据类型进行自动装配
@Autowire
private UserDao userDao;
Spring框架会自动将类型为UserDao的对象注入进来。
@Resource:默认是按照名称或者ID进行自动装配,只有找不到匹配的名称或者ID时才按照类型进项装配
@Resource(name="userDao")
private UserDao userDao;
Spring框架在运行时会根据名称或者ID为“userDao”的对象注入进来。