I、springboot基本概念
1.受管Bean
Spring中那些组成应用的主体以及由Spring IoC容器所管理的对象被称之为bean;
Bean就是由Spring容器初始化、装配以及被管理的对象
2.控制反转IOC和依赖注入DI
IoC实现由容器控制程序之间的关系,而非传统实现中,由程序代码直接操控,控制权由应用代码中转到了外部容器,控制权的转移,是所谓控制反转;
创建被调用者实例的工作通常由Spring容器来完成,然后注入调用者,因此也称为依赖注入
依赖注入:接口注入、设置注入、构造器注入
3.AOP面向切面编程
AOP即Aspect-Oriented Programming, 面向切面编程是一种新的方法论,是一种技术,不是设计模式,是对传统OOP(Object-Oriented Programming,面向对象编程)的补充
AOP 的主要编程对象是切面(aspect), 而切面模块化横切关注点
II、搭建简单的web服务器(SSH)
1.添加jar包
整合maven,在pom.xml中添加
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc6</artifactId> <version>1.5</version> <scope>system</scope> <systemPath>${project.basedir}/src/main/webapp/WEB-INF/lib/ojdbc6.jar</systemPath> </dependency> </dependencies>
2.整合Spring和web应用(在web.xml中添加)
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:app*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
3.整合struts2(在web.xml中添加)
<filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class> <init-param> <param-name>struts.devMode</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
4.整合Hibernate
a.添加database.properties文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=root
b.配置连接池(在applicationContext.xml中添加)
<context:property-placeholder location="classpath:database.properties" /> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" p:driverClassName="${jdbc.driver}" p:url="${jdbc.url}" p:username="${jdbc.username}" p:password="${jdbc.password}" destroy-method="close" />
c.配置SessionFactory(在applicationContext.xml中添加)
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" p:packagesToScan="com.yan.entity"(重点:使组件自动扫描特定的包以发现实体类的定义) p:dataSource-ref="dataSource"> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext (重点:使getCurrentSession不为null)</prop> </props> </property>
d.配置事务管理SessionFactory(在applicationContext.xml中添加)
<tx:annotation-driven />配置注解事务有效 <bean id="transactionManager" p:sessionFactory-ref="sessionFactory" class="org.springframework.orm.hibernate5.HibernateTransactionManager" />
5.定义带注解的实体类
在src/com/wcg/entity包下添加实体类
@Entity(name = "t_roles") //声明实体类,name是对应的表名称 @Cache(usage=CacheConcurrencyStrategy.READ_ONLY) //配置二级缓存的并发访问策略,read_only/read_write NONSTRICT_READ_WRITE TRANSACTIONAL public class RoleBean implements Serializable { private static final long serialVersionUID = -7132291370667604346L; @Id //声明主键 @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(length = 32, unique = true, nullable = false)//定义类说明,length字串长度unique唯一性约束,nullable非空约束 private String name; @Basic(fetch = FetchType.LAZY)//针对属性的加载策略,需要支持 @Column(length = 200) private String descn; @OneToMany(mappedBy = "role", cascade = CascadeType.ALL)//说明一对多关联,mapedby表示由对方负责维护两者之间的关联关系,cascade级联策略 private Set<UserBean> users = new HashSet<>();
6.定义DAO接口--IBaseDao
在src/com/wcg/dao包下添加DAO接口
public interface IBaseDao<T extends Serializable,ID extends Serializable> { T save(T record); T delete(T record); T load(ID id); T update(T record); List<T> selectByExample(T record, int... pages); int selectByExampleRowsNum(T record); //查询满足条件的一共有多少行 } //-------------------------- public interface IRoleDao extends IBaseDao<RoleBean, Long> { } //-------------------------- public class BaseDaoImpl<T extends Serializable, ID extends Serializable> implements IBaseDao<T, ID> { @Autowired private SessionFactory sessionFactory; private Class<T> recordClass; @SuppressWarnings("unchecked") public BaseDaoImpl() { this.recordClass = (Class<T>) (((ParameterizedType) getClass().getGenericSuperclass()) .getActualTypeArguments()[0]); } protected Session getSession() { return sessionFactory.getCurrentSession(); } @Override public T save(T record) { this.getSession().save(record); return record; } @Override public T delete(T record) { this.getSession().delete(record); return record; } @Override public T load(ID id) { return this.getSession().get(recordClass, id); } @Override public T update(T record) { this.getSession().update(record); return record; } @SuppressWarnings("unchecked") @Override public List<T> selectByExample(T record, int... pages) { Criteria criteria = this.getSession().createCriteria(recordClass); if(record != null) criteria.add(Example.create(record)); if(pages != null && pages.length > 0) criteria.setFirstResult(pages[0]); if(pages != null && pages.length > 1) criteria.setMaxResults(pages[1]); return criteria.list(); } //-------------------------- @Repository("roleDao")//声明DAO类型的受管bean,其中的value就是名称,类似于<bean>的id public class RoleDaoImpl extends BaseDaoImpl<RoleBean, Long> implements IRoleDao { }
7.定义业务
在src/com/wcg/biz包下添加Server接口
public interface IRoleServ { void create(RoleBean role); } //-------------------------- @Service //定义业务类型的受管bean,如果不定义名称,则默认名称就是类名称,首字母小写 @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) //声明事务,readOnly只读事务propagation事务传播特性 public class RoleServImpl implements IRoleServ { @Resource(name = "roleDao") private IRoleDao roleDao; @Transactional(readOnly = false, propagation = Propagation.REQUIRED) public void create(RoleBean role) { roleDao.save(role); }
8.定义Action
在src/com/wcg/action包下添加action类
@Controller //定义控制器类型的受管bean @Scope("prototype") //定义scope=prototype以保证Action的多实例 @Namespace("/") //Struts2的注解,表示名空间 @ParentPackage("struts-default") //Struts2的注解,定义继承的包名称 public class UserAction extends ActionSupport implements ModelDriven<UserBean>, SessionAware { private UserBean user = new UserBean(); private Map<String, Object> sessionAttribute; @Autowired private IUserServ userv; @Action(value = "tologin", results = { @Result(name = "success", location = "/WEB-INF/content/user/login.jsp") }) public String toLogin() throws Exception { return SUCCESS; }
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。