-
Spring如何管理Java普通类(Java类获取Spring容器的bean)
2017-05-15 22:50:59Spring如何管理Java普通类 Java类获取Spring容器的bean 获取spring的ApplicationContext方法一:在初始化时保存ApplicationContext对象
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); applicationContext.getBean("beanId");
这种方法会初始化Spring容器,重新加载applicationContext.xml文件,如果配置文件中有一些线程类或者定时任务,会执行两次。
方法二:不依赖于servlet,不需要注入的方式
WebApplicationContext ac = ContextLoader.getCurrentWebApplicationContext(); TestService testService= (TestService) wac.getBean("testService");
这种方法得等到服务器启动完成且Spring容器初始化结束之后才能使用。
方法三:继承自抽象类ApplicationObjectSupport
抽象类ApplicationObjectSupport提供getApplicationContext()方法,可以方便的获取到ApplicationContext。
Spring初始化时,会通过该抽象类的setApplicationContext(ApplicationContext context)方法将ApplicationContext 对象注入方法四:继承自抽象WebApplicationObjectSupport
类似上面方法,调用getWebApplicationContext()获取WebApplicationContext
方法五:实现接口ApplicationContextAware
实现该接口的setApplicationContext(ApplicationContext context)方法,并保存ApplicationContext 对象。
Spring初始化时,会通过该方法将ApplicationContext对象注入。后三种方法都是相似的,都是在普通的类中继承或实现相应的类或接口来获取spring 的ApplicationContext对象,但是在使用是一定要注意实现了这些类或接口的普通java类一定要在Spring 的配置文件application-context.xml文件中进行配置。否则获取的ApplicationContext对象将为null。
如下是实现了ApplicationContextAware接口的示例import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; /** * 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候中取出ApplicaitonContext. * */ public class SpringContextHolder implements ApplicationContextAware { private static ApplicationContext applicationContext; /** * 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量. */ public void setApplicationContext(ApplicationContext applicationContext) { SpringContextHolder.applicationContext = applicationContext; // NOSONAR } /** * 取得存储在静态变量中的ApplicationContext. */ public static ApplicationContext getApplicationContext() { checkApplicationContext(); return applicationContext; } /** * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型. */ @SuppressWarnings("unchecked") public static <T> T getBean(String name) { checkApplicationContext(); return (T) applicationContext.getBean(name); } /** * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型. */ @SuppressWarnings("unchecked") public static <T> T getBean(Class<T> clazz) { checkApplicationContext(); return (T) applicationContext.getBeansOfType(clazz); } /** * 清除applicationContext静态变量. */ public static void cleanApplicationContext() { applicationContext = null; } private static void checkApplicationContext() { if (applicationContext == null) { throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder"); } } }
在spring配置文件中加入
<bean class="com.xxxxx.SpringContextHolder" lazy-init="false"/>
参考:
http://blog.itpub.net/143526/viewspace-1058439/
http://www.cnblogs.com/cxyj/p/3906355.html -
java——类——类管理
2017-06-16 17:44:23每个源文件都可作为启动项,如果源文件作为启动项,那么必须包含一个与源文件名同名class(public无要求),启动时根据源文件名找到对应类作为启动加载类,如果找不到对应类,则runtime error,因此如果源文件内含...源文件命名
- 每个源文件至多允许含一个public class(允许无public class),含public class源文件public class名必须与源文件名一致,无public class源文件,源文件命名无限制
程序启动
- 每个源文件都可作为启动项,如果源文件作为启动项,那么必须包含一个与源文件名同名class(public无要求),启动时根据源文件名找到对应类作为启动加载类,如果找不到对应类,则runtime error,因此如果源文件内含public class且作为启动项,则该public class必然是启动加载类
- 启动加载类必须包含public static void main(String[] args)方法成员作为java程序执行入口(除形参名args可任意,其他不可更改)
classpath
- classpath类似于c++中的header search paths或library search paths,是一个目录列表
- header search paths是头文件search目录列表
- library search paths是库文件search目录列表
- classpath是.class文件加载时jvm search目录列表
package
- 相对于classpath相对路径(目录),与classpath一起组成.class文件所在完整目录
import
- import类似于c++中的#include,用来导入.class文件,只有导入.class文件,该.class文件才可能被jvm加载,import导入.class文件支持文件通配符
- 当前可用类名中同一类名不允许对应多个可加载.class文件,否则引用该类时二义性error(jvm不知道加载哪个.class文件),但如果类访问权限不允许,则引用该类时不构成二义性error(比如import两个同名类,但这两个同名类访问权限并非同为public,则引用该类不构成二义性error)
- 每个源文件默认import java.util.*
-
JAVA学生宿舍管理系统
2019-01-22 21:28:14system.java (系统管理界面) sql.java (数据库操作,包括连接、断开、增删改查等操作) 一、登陆界面及代码 主要代码: 登陆按钮事件 public void actionPerformed(ActionEvent e) { // TODO Auto-...需要的工具
1.SQL Server
2.Eclipse
3.JDBC连接数据库驱动
https://download.microsoft.com/download/A/F/B/AFB381FF-7037-46CE-AF9B-6B1875EA81D7/sqljdbc_6.0.8112.200_chs.exe功能实现
分为三大类
1.land.java (登陆界面)
2.system.java (系统管理界面)
3.sql.java (数据库操作,包括连接、断开、增删改查等操作)一、登陆界面及代码
部分代码:
登陆按钮事件
public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if((JButton)e.getSource()== buttonLand) { String name = textName.getText().trim(); String password = String.valueOf(textPassword.getPassword()).trim(); int num = sq.landing(name, password); if(num==1) { JOptionPane.showMessageDialog(frame, "欢迎进入学生宿舍管理系统!","提示:",JOptionPane.PLAIN_MESSAGE); system system = new system(); frame.dispose(); } else { JOptionPane.showMessageDialog(frame, "账号或者密码错误!","提示:",JOptionPane.ERROR_MESSAGE); } } }
二、系统管理界面及代码**(这里只添加了俩个表,多少表都是一样的道理**)
增加数据:点击增加按钮会出现一空白行,填写完点击保存即可
保存(更新)数据:直接在表中进行相应的操作,再点击保存即可
删除数据:选择某行,点击删除按钮即可
部分代码://--------------------------------------按钮事件-------------------------------- @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub //------------------------------- 删除----------------------------- String tableName = null; String key1 = null; if((JButton)e.getSource()==buttonDelete) { if(paneParent.getSelectedIndex()==1) { tableName = "学生信息表"; key1 = "sno"; } if(paneParent.getSelectedIndex()==2) { tableName = "宿舍信息表"; key1 = "dno"; } int row = table.getSelectedRow(); if(row!=-1) { String key2 = (String) tableModel.getValueAt(row, 0); int result = JOptionPane.showConfirmDialog(null, "确定要删除吗?","请确认",JOptionPane.YES_NO_OPTION); if(result==JOptionPane.OK_OPTION) { String sql = "delete from "+tableName+" where "+key1+"="+key2; int num = sq.delete(sql); if(num>0) { tableModel.removeRow(row); } } } else { JOptionPane.showMessageDialog(null, "请选择要删除的行!","提示:",JOptionPane.ERROR_MESSAGE); } } //------------------------------保存------------------------ if((JButton)e.getSource()==buttonSave) { int result = JOptionPane.showConfirmDialog(null, "请确认数值已经更改,否则保存无效","请确认",JOptionPane.YES_NO_OPTION); if(result==JOptionPane.OK_OPTION) { int row = table.getRowCount(); int column = table.getColumnCount(); String[][]valueRow= new String[row][column]; String[] sqlvalue = new String[row]; for(int i = 0; i < row; i++) { for(int j = 0; j < column; j++) { valueRow[i][j] = table.getValueAt(i, j).toString(); } } if(paneParent.getSelectedIndex()==1) { for(int i =0;i<row;i++) { String sql = "insert into 学生信息表"+" values ("+valueRow[i][0].toString()+","+valueRow[i][1].toString()+","+valueRow[i][2].toString()+","+valueRow[i][3].toString()+","+valueRow[i][4].toString()+","+valueRow[i][5].toString()+")"; sqlvalue[i]=sql.toString(); } data = sq.Save(sqlvalue,"学生信息表",row, column); tableModel.setDataVector(data,dataTitle); } if(paneParent.getSelectedIndex()==2) { for(int i =0;i<row;i++) { String sql = "insert into 宿舍信息表"+" values ("+valueRow[i][0].toString()+","+valueRow[i][1].toString()+")"; sqlvalue[i]=sql.toString(); } data = sq.Save(sqlvalue,"宿舍信息表",row, column); tableModel.setDataVector(data,TitleDormitor); } } } //------------------------------增加--------------------------- if((JButton)e.getSource()==buttonIncrease) { tableModel.addRow(new Vector<>()); } }
三、sql.java (重要)
public class SQL { public Connection conn; public Statement st; public ResultSet rs; //----------------------------获取链接-------------------------------- public Connection getConn() throws SQLException, ClassNotFoundException { String driverClassName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; String url = "jdbc:sqlserver://localhost:1433;databaseName=学习宿舍"; //:1433为数据库默认端口号,学习宿舍为数据库名字 String user = "sa"; //登录用户名 String password = "123456"; //登录密码 try { Class.forName(driverClassName); conn = DriverManager.getConnection(url, user, password); System.out.println("数据库连接成功"); } catch (SQLException ex1) { System.out.println("数据库连接失败"); } return conn; } //-----------------------------------关闭链接---------------------------------- public void Close() { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } try { st.close(); } catch (SQLException e1) { e1.printStackTrace(); } try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } //----------------------------------------登陆--------------------------------- public int landing(String name1,String password1) { int num = 0; String sql = "select *from 用户表"; try{ getConn(); st = conn.createStatement(); rs = st.executeQuery(sql); while(rs.next()) { String name = rs.getString(1).trim(); String password = rs.getString(2).trim(); if(name.equals(name1)&&password.equals(password1)) { num = 1; } } }catch (SQLException e) { // TODO: handle exception } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } Close(); return num; } //--------------------------------查询------------------------------- public Vector<Vector<Object>> query(String tableName,int column) { int num = 0; String sql = "select *from "+tableName; Vector<Vector<Object>> data = new Vector<Vector<Object>>(); try{ getConn(); st = conn.createStatement(); rs=st.executeQuery(sql); while(rs.next()) { Vector<Object> rowdata = new Vector<Object>(); for(num=1;num<=column;num++) { rowdata.add(rs.getString(num)); } data.add(rowdata); } }catch(SQLException ex1) { System.out.println("失败"+ex1); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } Close(); return data; } //---------------------------------------删除---------------------------------- public int delete(String sql) { int num = 0; try{ getConn(); st = conn.createStatement(); num = st.executeUpdate(sql); }catch (SQLException e) { // TODO: handle exception } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } Close(); return num; } //-------------------------------------保存------------------------------------- public Vector<Vector<Object>> Save(String[] sqlvalue,String tableName,int row,int column) { Vector<Vector<Object>> data = new Vector<Vector<Object>>(); try{ getConn(); st = conn.createStatement(); st.executeUpdate("delete from "+tableName); for(int i =0;i<row;i++) { st.executeUpdate(sqlvalue[i].toString()); } data = query(tableName, column); }catch (SQLException e) { // TODO: handle exception } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return data; } }
数据库连接账号密码及表名
**
这个是数据库的连接账号和密码123456
这个是用户表结构和登陆账号和密码(可自行修改)
**
宿舍信息表结构**
**
学生信息表结构**
## 需要源码,点赞关注截图,发邮箱到1397195447@qq.com
-
管理Java类文件
2013-03-20 20:29:33如果程序的规模越来越大,那么类文件也会越来越多,管理起来也会越来越麻烦,很容易发生命名的冲突。因此,java中引入了"包"(package)的概念。 一、内部类 在类中还可以再定义类,这种类叫做内部类(Inner ...在java中,每一个定义好的类,在编译的时候,都会对应地产生一个.class文件。如果程序的规模越来越大,那么类文件也会越来越多,管理起来也会越来越麻烦,很容易发生命名的冲突。因此,java中引入了"包"(package)的概念。
一、内部类
在类中还可以再定义类,这种类叫做内部类(Inner Class)。使用内部类主要有三个好处:一是可以任意地访问对应的外部类的私有(private)成员;二是如果一个内部类只服务于对应的外部类,那么外界就不必知道有这个内部类的存在;三是对于外部类来说,内部类可以将一系列数据类型“打包”,就像C++的类中再定义结构体一样。当然类的功能要比结构体强大多了。
1、访问外部类的prvate成员
import static java.lang.System.out; class Outer { private int x = 0; //内部类Inner class Inner { public int accessOuter() //访问外部类的private成员 { return x; } } public Inner getInner() //返回内部类对象 { return new Inner(); } public static void main(String[] args) { Outer objOut = new Outer(); out.println(objOut.getInner().accessOuter()); } }
可以看到,程序打印出了外部类的private成员x的值。
2、将数据类型打包
InnerDemo类表示一个点集,而点集中的每一个点元素就可以用内部类来定义表示。public class InnerDemo { //内部类Point,表示一个点 private class Point { private int x,y; Point(int x,int y) { this.x = x; this.y = y; } public String toString() { return "(x = " + x + ",y = " + y + ")"; } } //创建3个部类Point对象 Point[] pt = new Point[]{new Point(1,1),new Point(2,2),new Point(3,3)}; //输出点集 public void getAllPoints() { for(Point point : pt) { System.out.println(point); } } public static void main(String[] args) { InnerDemo inner = new InnerDemo(); inner.getAllPoints(); } }
程序运行结果:
对于一个包含内部类的类,程序编译后会产生一个名为 "外部类名$内部类名.class" 的类文件。如上例,编译后会生成InnerDemo$Point.class文件。由于Point类仅仅服务于其对应的外部InnerDemo类,因而在实际使用InnerDemo类的时候,我们不必关心Point类的存在。
二、匿名内部类
匿名内部类可以不用声明类名称,直接使用new关键字来产生一个对象:
这样的好处是,对于一些接口或者方法的参数类型是一个类的引用的时候,我们不必单独定义一个新的类去产生一个对象再把对象传进去,直接使用匿名内部类可以省略类的定义。如getInner方法需要一个Point类的对象,那么我们可以这样写:new Object(){ public void doSomethig(){ //... ... } }
值得注意的是,如果在一个匿名的内部类中想要访问外部的局部变量,那么就必须将这个要被访问的变量声明为final.否则在编译的时候就会报错,如:getInner(new Point() public void method() { //do something } );
public void method() { int x = 100; //没有声明为final Object obj = new Object(){ public String toString() { System.out.println(x); //访问外部的x变量 return "New Object!"; } }; }
那么,为什么编译器要强制我们把x声明为final?这是因为,在匿名内部类中访问x时,内部类中访问的只是变量x的一份拷贝,如果在匿名内部类中修改了变量x,那么这种修改是不会影响到外部的变量x的。所以把x声明为final后,就起到一个提醒的作用,表示程序员不可以在内部类中修改x的值。这样就降低了