SpringWeb入门(一)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Heavy_Dream/article/details/79953607

项目结构:


核心配置文件applicationContext.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"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">


<!-- 开启注解扫描 -->
<!-- base-package扫描的包及子包下的类 -->
<!-- 使用annotation(@注解方式) 自动注册bean,并保证@Required,@Autowired的属性被注入 -->

<context:component-scan base-package="edu.cloud"></context:component-scan>

</beans>

控制器Action:

package edu.cloud.action;


import javax.annotation.Resource;


import org.springframework.stereotype.Controller;


import edu.cloud.service.UserService;


@Controller("userAction")
public class UserAction {
@Resource(name="userService")
private UserService userService;

public String addUser() {
userService.save();
return null;
}

}

服务层Service:

package edu.cloud.service;


import javax.annotation.Resource;


import org.springframework.stereotype.Service;


import edu.cloud.dao.UserDao;


@Service("userService")
public class UserService {
@Resource(name="userDao")
private UserDao userDao;

public void save() {
userDao.save();
}

}

Dao层:

package edu.cloud.dao;


import org.springframework.stereotype.Repository;


@Repository("userDao")
public class UserDao {


public void save() {
System.out.println("连接数据库进行保存");
}


}

实体Bean:

/**
 * 
 */
package edu.cloud.entity;


/**
 * @author huangbaida
 * @description 
 * @date 2018�?1�?21�?
 */
public class User {
private Integer id;
private String name;
private Integer age;

public User() {
}

public User(int id, String name) {
this.id = id;
this.name = name;
}


public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}

public void init_user() {
System.out.println("对象初始化调用?");
}
public void destroy_user() {
System.out.println("对象销毁调用?");
}


@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
}


}

测试:

package edu.cloud.entity;


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


import edu.cloud.action.UserAction;


public class Test {
public static void main(String[] args) {
//获取IOC容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");

UserAction userAction = (UserAction) applicationContext.getBean("userAction");
userAction.addUser();
}
}

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页