spring的作用和配置
1.建立一个实体类,建立一个dao类
package com.sun.model; public class User { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
package com.sun.dao; import com.sun.model.User; public class UserDAO { public void save(User u) { System.out.println("saved"); } }
2.将user存入数据库,一般的情况是数据库连接,然后session.save(user);但是有了service这一层,就将这句话给封装了,变成了service.save(u),我们不再接触数据库那一层了。
package com.sun.service; import com.sun.dao.UserDAO; import com.sun.model.User; public class UserService { private UserDAO userdao; public UserDAO getUserdao() { return userdao; } public void setUserdao(UserDAO userdao) { this.userdao = userdao; } public void add(User u) { this.userdao.save(u); } }
package com.sun.service; import com.sun.dao.UserDAO; import com.sun.model.User; public class Test { public static void main(String[] args) { UserService service=new UserService(); UserDAO userdao=new UserDAO(); service.setUserdao(userdao); User u=new User(); service.add(u); } }
3.将service.add(u);与userdao.save(u);比较就知道service的大致作用了
4.需要的spring jar包
5.写一个程序测试(spring 的作用就是你现在还不用new 一个service了,它来帮你完成即控制反转的含义)
6.service代码
package com.sun.spring; public interface UserService { public void addUser(); }
package com.sun.spring; public class serviceimpl implements UserService { public void addUser() { System.out.println("hello"); } }
7.加入.xml文件,文件帮助内容在下面找
8.配置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 definitions here --> <bean id="userService" class="com.sun.spring.serviceimpl"> </bean> </beans>
9.测试
package com.sun.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] agrs) {
String xmlPath="com/sun/spring/beans.xml";
ApplicationContext appicationcantext=new ClassPathXmlApplicationContext(xmlPath);
UserService userservice=(UserService) appicationcantext.getBean("userService");
userservice.addUser();
}
}
10.spring就是帮你管类文件的,所有你需要new的它都帮你用配置文件统一完成。