java配置文件怎么写
1.java配置文件怎么写
假设有如下xml配置文件config.xml:
kiyhosinkiang100
可以用以下代码访问:
import org.apache.commons.configuration.;
import org.apache.commons.configuration.XMLConfiguration;
public class XmlConfigDemo {
public static void main(String[] args) {
try {
XMLConfiguration config = new XMLConfiguration("config.xml");
System.out.println(config.getList("name"));
System.out.println(config.getInt("info.age"));
} catch ( e) {
e.printStackTrace();
}
}
}
2.java配置文件怎么写
假设有如下xml配置文件config.xml:<?xml version="1.0" encoding="utf-8" ?>
3.怎样读取和写我自己写的一个java配置文件
import java.io.File;import org.dom4j.Document;import org.dom4j.Element;import org.dom4j.io.SAXReader;/** * @Title: JavaBeanCreater.java * @Package liaodong.xiaoxiao.dom4j.sxd.bean * @Description: TODO(根据xml配置文件,生成javabean) * @author 辽东小小 * @date 2012-3-1 上午09:13:25 * @version V1.0 */public class JavaBeanCreater{ public static void main(String[] args) { //xml的存放路径 String xmlPath = "D:\\test\\javabean.xml"; File xmlFile = new File(xmlPath); StringBuffer sBuffer = new StringBuffer("public class "); SAXReader sReader = new SAXReader(); Document document; try { //读取xml文件,返回document对象 document = sReader.read(xmlFile); //获取根元素 Element rootElement = document.getRootElement(); // String className = rootElement.elementText("classname"); sBuffer.append(className).append("\n"); sBuffer.append("{\n"); String nature = rootElement.elementText("nature"); String natures[] = nature.split(","); //构造成员变量 for (String n : natures) { sBuffer.append("private String ").append(n).append(";\n"); } //构造set/get方法 for (String n : natures) { String methodName = n.substring(0, 1).toUpperCase()+n.substring(1); //拼写set方法 sBuffer.append("public void set").append(methodName).append("( String ").append(n).append(" )\n{"); sBuffer.append("this.").append(n).append(" = ").append(n).append(";\n}\n"); //拼写get方法 sBuffer.append("public String get").append(methodName).append(" ( )\n{\n"); sBuffer.append("return ").append(n).append(";\n}\n"); } //language 方法跟上面的类似 省略。
//写文件的方法也省略了。
sBuffer.append("}"); System.out.println(sBuffer.toString()); //}catch(Exception e){ e.printStackTrace(); } }}用Dom4j解析的xml##############################################################运行结果为:public class animal{private String name;private String food;private String age;public void setName( String name ){this.name = name;}public String getName ( ){return name;}public void setFood( String food ){this.food = food;}public String getFood ( ){return food;}public void setAge( String age ){this.age = age;}public String getAge ( ){return age;}}。
4.配置文件在java 中怎么创建
1.一般在scr下面新建一个属性文件*.properties,如a.properties 然后在Java程序中读取或操作这个属性文件。
代码实例 属性文件a.properties如下:name=root pass=liu key=value 读取a.properties属性列表,与生成属性文件b.properties。代码如下:1 import java.io.BufferedInputStream; 2 import java.io.FileInputStream; 3 import java.io.FileOutputStream; 4 import java.io.InputStream; 5 import java.util.Iterator; 6 import java.util.Properties; 7 8 public class PropertyTest { 9 public static void main(String[] args) { 10 Properties prop = new Properties(); 11 try{12 //读取属性文件a.properties13 InputStream in = new BufferedInputStream (new FileInputStream("a.properties"));14 prop.load(in); ///加载属性列表15 Iterator
Properties类继承自Hashtable类并且实现了Map接口,也是使用一种键值对的形式来保存属性集。不过Properties有特殊的地方,就是它的键和值都是字符串类型。
*.properties文件的注释用#。配置数据的时候是以键值对的形式,调用的时候和修改的时候也是操作键值对。
2.当然还可以用*.xml来配置,位置一般在一个包下面。例如com.styspace包下面的config.properties文件。
xml version="1.0" encoding="gbk"?> 100001 123
5.Java中的properties配置文件怎么写,代码
public static void main(String[] args) {
Properties p = new Properties();
p.setProperty("id", "user1");
p.setProperty("password", "123456");
try{
PrintStream stm = new PrintStream(new File("e:\test.properties"));
p.list(stm);
} catch (IOException e) {
e.printStackTrace();
}
}
6.java 怎么读取配置文件
一.读取xml配置文件
(一)新建一个java bean(HelloBean. java)
java代码
(二)构造一个配置文件(beanConfig.xml)
xml 代码
(三)读取xml文件
1.利用
java代码
2.利用FileSystemResource读取
java代码
二.读取properties配置文件
这里介绍两种技术:利用spring读取properties 文件和利用java.util.Properties读取
(一)利用spring读取properties 文件
我们还利用上面的HelloBean. java文件,构造如下beanConfig.properties文件:
properties 代码
helloBean.class=chb.demo.vo.HelloBean
helloBean.helloWorld=Hello!chb!
属性文件中的"helloBean"名称即是Bean的别名设定,.class用于指定类来源。
然后利用org.springframework.beans.factory.support.来读取属性文件
java代码
(二)利用java.util.Properties读取属性文件
比如,我们构造一个ipConfig.properties来保存服务器ip地址和端口,如:
properties 代码
ip=192.168.0.1
port=8080
三.读取位于Jar包之外的properties配置文件
下面仅仅是列出读取文件的过程,剩下的解析成为properties的方法同上
1 FileInputStream reader = new FileInputStream("config.properties");
2 num = reader.read(byteStream);
3 ByteArrayInputStream inStream = new ByteArrayInputStream(byteStream, 0, num);
四.要读取的配置文件和类文件一起打包到一个Jar中
String currentJarPath = URLDecoder.decode(YourClassName.class.getProtectionDomain().getCodeSource().getLocation().getFile(), "UTF-8"); //获取当前Jar文件名,并对其解码,防止出现中文乱码
JarFile currentJar = new JarFile(currentJarPath);
JarEntry dbEntry = currentJar.getJarEntry("包名/配置文件");
InputStream in = currentJar.getInputStream(dbEntry);
//以上YourClassName是class全名,也就是包括包名
修改:
JarOutputStream out = new FileOutputStream(currentJarPath);
out.putNextEntry(dbEntry);
out.write(byte[] b, int off, int len); //写配置文件
。。
out.close();
7.怎样读取和写我自己写的一个java配置文件
import java.io.File;import org.dom4j.Document;import org.dom4j.Element;import org.dom4j.io.SAXReader;/** * @Title: JavaBeanCreater.java * @Package liaodong.xiaoxiao.dom4j.sxd.bean * @Description: TODO(根据xml配置文件,生成javabean) * @author 辽东小小 * @date 2012-3-1 上午09:13:25 * @version V1.0 */public class JavaBeanCreater{ public static void main(String[] args) { //xml的存放路径 String xmlPath = "D:\\test\\javabean.xml"; File xmlFile = new File(xmlPath); StringBuffer sBuffer = new StringBuffer("public class "); SAXReader sReader = new SAXReader(); Document document; try { //读取xml文件,返回document对象 document = sReader.read(xmlFile); //获取根元素 Element rootElement = document.getRootElement(); // String className = rootElement.elementText("classname"); sBuffer.append(className).append("\n"); sBuffer.append("{\n"); String nature = rootElement.elementText("nature"); String natures[] = nature.split(","); //构造成员变量 for (String n : natures) { sBuffer.append("private String ").append(n).append(";\n"); } //构造set/get方法 for (String n : natures) { String methodName = n.substring(0, 1).toUpperCase()+n.substring(1); //拼写set方法 sBuffer.append("public void set").append(methodName).append("( String ").append(n).append(" )\n{"); sBuffer.append("this.").append(n).append(" = ").append(n).append(";\n}\n"); //拼写get方法 sBuffer.append("public String get").append(methodName).append(" ( )\n{\n"); sBuffer.append("return ").append(n).append(";\n}\n"); } //language 方法跟上面的类似 省略。
//写文件的方法也省略了。
sBuffer.append("}"); System.out.println(sBuffer.toString()); //}catch(Exception e){ e.printStackTrace(); } }}用Dom4j解析的xml##############################################################运行结果为:public class animal{private String name;private String food;private String age;public void setName( String name ){this.name = name;}public String getName ( ){return name;}public void setFood( String food ){this.food = food;}public String getFood ( ){return food;}public void setAge( String age ){this.age = age;}public String getAge ( ){return age;}}。
properties配置文件怎么写
1.Java中的properties配置文件怎么写,代码
public static void main(String[] args) {
Properties p = new Properties();
p.setProperty("id", "user1");
p.setProperty("password", "123456");
try{
PrintStream stm = new PrintStream(new File("e:\test.properties"));
p.list(stm);
} catch (IOException e) {
e.printStackTrace();
}
}
2.properties文件怎么写
InputStream in = 类名.class.getClassLoader().getResourceAsStream("propertes名字.properties");
Properties prop = new Properties();
prop.load(in)
oracleDb_Driver = prop.getProperty("oracleDb_Driver-properties里面的字段");
3.java的properties文件怎么写
最常用读取properties文件的方法InputStream in = getClass().getResourceAsStream("资源Name");这种方式要求properties文件和当前类在同一文件夹下面。
如果在不同的包中,必须使用:InputStream ins = this.getClass().getResourceAsStream("/cn/zhao/properties/testPropertiesPath2.properties");Java中获取路径方法获取路径的一个简单实现反射方式获取properties文件的三种方式1 反射方式获取properties文件最常用方法以及思考:Java读取properties文件的方法比较多,网上最多的文章是"Java读取properties文件的六种方法",但在Java应用中,最常用还是通过java.lang.Class类的getResourceAsStream(String name) 方法来实现,但我见到众多读取properties文件的代码中,都会这么干:InputStream in = getClass().getResourceAsStream("资源Name");这里面有个问题,就是getClass()调用的时候默认省略了this!我们都知道,this是不能在static(静态)方法或者static块中使用的,原因是static类型的方法或者代码块是属于类本身的,不属于某个对象,而this本身就代表当前对象,而静态方法或者块调用的时候是不用初始化对象的。问题是:假如我不想让某个类有对象,那么我会将此类的默认构造方法设为私有,当然也不会写别的共有的构造方法。
并且我这个类是工具类,都是静态的方法和变量,我要在静态块或者静态方法中获取properties文件,这个方法就行不通了。那怎么办呢?其实这个类就不是这么用的,他仅仅是需要获取一个Class对象就可以了,那还不容易啊-- 取所有类的父类Object,用Object.class难道不比你的用你正在写类自身方便安全吗 ?呵呵,下面给出一个例子,以方便交流。
import java.util.Properties; import java.io.InputStream; import java.io.IOException; /** * 读取Properties文件的例子 * File: TestProperties.java * User: leizhimin * Date: 2008-2-15 18:38:40 */ public final class TestProperties { private static String param1; private static String param2; static { Properties prop = new Properties(); InputStream in = Object. class .getResourceAsStream( "/test.properties" ); try { prop.load(in); param1 = prop.getProperty( "initYears1" ).trim(); param2 = prop.getProperty( "initYears2" ).trim(); } catch (IOException e) { e.printStackTrace(); } } /** * 私有构造方法,不需要创建对象 */ private TestProperties() { } public static String getParam1() { return param1; } public static String getParam2() { return param2; } public static void main(String args[]){ System.out.println(getParam1()); System.out.println(getParam2()); } } 运行结果: 151 152 当然,把Object.class换成int.class照样行,呵呵,大家可以试试。另外,如果是static方法或块中读取Properties文件,还有一种最保险的方法,就是这个类的本身名字来直接获取Class对象,比如本例中可写成TestProperties.class,这样做是最保险的方法2 获取路径的方式:File fileB = new File( this .getClass().getResource( "" ).getPath()); System. out .println( "fileB path: " + fileB); 2.2获取当前类所在的工程名:System. out .println("user.dir path: " + System. getProperty ("user.dir"))3 获取路径的一个简单的Java实现 /** *获取项目的相对路径下文件的绝对路径 * * @param parentDir *目标文件的父目录,例如说,工程的目录下,有lib与bin和conf目录,那么程序运行于lib or * bin,那么需要的配置文件却是conf里面,则需要找到该配置文件的绝对路径 * @param fileName *文件名 * @return一个绝对路径 */ public static String getPath(String parentDir, String fileName) { String path = null; String userdir = System.getProperty("user.dir"); String userdirName = new File(userdir).getName(); if (userdirName.equalsIgnoreCase("lib") || userdirName.equalsIgnoreCase("bin")) { File newf = new File(userdir); File newp = new File(newf.getParent()); if (fileName.trim().equals("")) { path = newp.getPath() + File.separator + parentDir; } else { path = newp.getPath() + File.separator + parentDir + File.separator + fileName; } } else { if (fileName.trim().equals("")) { path = userdir + File.separator + parentDir; } else { path = userdir + File.separator + parentDir + File.separator + fileName; } } return path; } 4 利用反射的方式获取路径:InputStream ips1 = Enumeration . class .getClassLoader() .getResourceAsStream( "cn/zhao/enumStudy/testPropertiesPath1.properties" ); InputStream ips2 = Enumeration . class .getResourceAsStream( "testPropertiesPath1.properties" ); InputStream ips3 = Enumeration . class .getResourceAsStream( "properties/testPropertiesPath2.properties" );。
4.Java中的properties配置文件怎么写,代码
public static void main(String[] args) { Properties p = new Properties(); p.setProperty("id", "user1"); p.setProperty("password", "123456"); try{ PrintStream stm = new PrintStream(new File("e:\test.properties")); p.list(stm); } catch (IOException e) { e.printStackTrace(); }}。
5.如何写一个.properties文件,如何调用
properties属性文件内容都是以键值对形式存在的,比如我写一个叫test.properties的文件,打开后可以再里面写如:name=Tom
而在java类中需要new一个Properties类的对象,如下:
Properties properties = new Properties();
接下来需要获取test.properties的文件路径:
String path = Thread.currentThread().getContextClassLoader().getResource("test.properties").getPath();
然后加载该文件:
properties.load(new FileInputStream(path));
最后你就可以get它的属性了:
String name_1=properties.getProperty("name");
这个name_1的值就是“TOM”了。
(因为涉及到文件流,所以加载那一步需要try catch,根据编译器提示自己加吧)
6.JAVa读取配置文件位置ReaderProperties类要怎么写
package com; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties;/*** 读取配置文件properties文件*/ public class Configuration { private Properties pro; private FileInputStream inputFile; private FileOutputStream outputFile; public Configuration(){ pro = new Properties(); } /** * 初始化Configuration类 * @param filePath 要读取的配置文件的路径+名称 */ public Configuration(String filePath){ pro = new Properties(); try { //读取属性文件 inputFile = new FileInputStream(filePath); //装载文件 pro.load(inputFile); inputFile.close(); } catch (FileNotFoundException e) { System.out.println("读取属性文件--->失败!- 原因:文件路径错误或者文件不存在"); e.printStackTrace(); } catch (IOException e) { System.out.println("装载文件--->失败!"); e.printStackTrace(); } } /** * 得到key值 * @param key 取得其值的键 * @return 取得键值 */ public String getValue(String key){ if(pro.containsKey(key)){ String value = pro.getProperty(key); return value; }else{ return ""; } } /** * 得到key值 * @param filePath properties文件的路径+文件名 * @param key 取得其值的键 * @return 取得键值 */ public String getValue(String filePath, String key){ try { String value = ""; inputFile = new FileInputStream(filePath); pro.load(inputFile); inputFile.close(); if(pro.contains(key)){ value = pro.getProperty(key); return value; }else{ return ""; } } catch (FileNotFoundException e) { e.printStackTrace(); return ""; } catch (IOException e) { e.printStackTrace(); return ""; } catch (Exception e) { e.printStackTrace(); return ""; } } /** * 清除properties文件中所有的key和其值 */ public void clear(){ pro.clear(); } /** * 改变或添加一个key的值 * 当key存在于properties文件中时该key的值被value所代替, * 当key不存在时,该key的值是value * @param key 要存入的键 * @param value 要存入的值 */ public void setValue(String key, String value){ pro.setProperty(key, value); } /** * 将更改后的文件数据存入指定的文件中,该文件可以事先不存在 * @param fileName 文件路径+文件名称 * @param description 对该文件的描述 */ public void saveFile(String fileName, String description){ try { outputFile = new FileOutputStream(fileName); pro.store(outputFile, description); outputFile.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException ioe){ ioe.printStackTrace(); } } /** * 测试方法 * @param args */ public static void main(String[] args) { Configuration conf = new Configuration(".\\.\\WebContent\\WEB-INF\\jdbc.properties"); String value = conf.getValue("hibernate.dialect"); System.out.println(value); } }。
7.springboot application.properties 写多个配置文件怎么写
springboot application.properties 写多个配置文件的方法:# 文件编码 banner.charset= UTF-8# 文件位置 banner.location= classpath:banner.txt# 日志配置# 日志配置文件的位置。
例如对于Logback的`classpath:logback.xml` logging.config= # %wEx#记录异常时使用的转换字。logging.exception-conversion-word= # 日志文件名。
例如`myapp.log` logging.file= # 日志级别严重性映射。 例如`logging.level.org.springframework = DEBUG` logging.level.*= # 日志文件的位置。
例如`/ var / log logging.path= # 用于输出到控制台的Appender模式。 只支持默认的logback设置。
logging.pattern.console=# 用于输出到文件的Appender模式。 只支持默认的logback设置。
logging.pattern.file= # 日志级别的Appender模式(默认%5p)。 只支持默认的logback设置。
logging.pattern.level=#注册日志记录系统的初始化挂钩。logging.register-shutdown-hook= false# AOP 切面# 添加@。
spring.aop.auto= true# 是否要创建基于子类(CGLIB)的代理(true),而不是基于标准的基于Java接口的代理(false)。spring.aop.proxy-target-class= false# 应用程序上下文初始化器# 应用指标。
spring.application.index= # 应用程序名称。spring.application.name= # 国际化(消息源自动配置)# spring.messages.basename= messages# 以逗号分隔的基础名称列表,每个都在ResourceBundle约定之后。
# 加载的资源束文件缓存到期,以秒为单位。 设置为-1时,软件包将永久缓存。
spring.messages.cache-seconds= -1# 消息编码。spring.messages.encoding= UTF-8# 设置是否返回到系统区域设置,如果没有找到特定语言环境的文件。
spring.messages.fallback-to-system-locale= true# REDIS (Redis 配置)# 连接工厂使用的数据库索引。spring.redis.database= 0# Redis服务器主机。
spring.redis.host= localhost# 登录redis服务器的密码。spring.redis.password= # 给定时间池可以分配的最大连接数。
使用负值为无限制。spring.redis.pool.max-active= 8# 池中“空闲”连接的最大数量。
使用负值来表示无限数量的空闲连接。spring.redis.pool.max-idle= 8# 连接分配在池耗尽之前在抛出异常之前应阻止的最大时间量(以毫秒为单位)。
使用负值无限期地阻止。spring.redis.pool.max-wait= -1# 定义池中维护的最小空闲连接数。
此设置只有在正值时才有效果。spring.redis.pool.min-idle= 0# redis服务器端口 spring.redis.port= 6379# redis服务器名称 spring.redis.sentinel.master=# spring.redis.sentinel.nodes= # 连接超时(毫秒)。
spring.redis.timeout= 0# 管理员 (Spring应用程序管理员JMX自动配置)# 开启应用管理功能。spring.application.admin.enabled= false# JMX应用程序名称MBean。
spring.application.admin.jmx-name= org.springframework.boot:type= Admin,name= SpringApplication# 自动配置# 自动配置类排除。spring.autoconfigure.exclude= # spring 核心配置# 跳过搜索BeanInfo类。
spring.beaninfo.ignore= true# spring 缓存配置# 由底层缓存管理器支持的要创建的缓存名称的逗号分隔列表。spring.cache.cache-names= # 用于初始化EhCache的配置文件的位置。
spring.cache.ehcache.config= # 用于创建缓存的规范。 检查CacheBuilderSpec有关规格格式的更多细节。
spring.cache.guava.spec= # 用于初始化Hazelcast的配置文件的位置。spring.cache.hazelcast.config= # 用于初始化Infinispan的配置文件的位置。
spring.cache.infinispan.config= # 用于初始化缓存管理器的配置文件的位置。spring.cache.jcache.config= # 用于检索符合JSR-107的缓存管理器的CachingProvider实现的完全限定名称。
只有在类路径上有多个JSR-107实现可用时才需要。spring.cache.jcache.provider= # 缓存类型,默认情况下根据环境自动检测。
spring.cache.type= # spring配置 (配置文件应用侦听器)# 配置文件位置。spring.config.location= # 配置文件名。
spring.config.name= application Springboot的多配置文件是指:系统中存在多个配置文件,在不同的运行环境使用不同的配置文件即可。启动项目的方法一般有两种 :1、运行RootApplication中的main方法。
2、使用命令:mvn spring-boot:run 这两方法默认都是使用application.properties中的配置信息,如果有指spring.profiles.active则使用指定的配置信息,这种方式一般用在产品运行时,在开发和测试的时候则需要指定配置文件。
8.如何读取.properties文件配置的两种方法
[html] view plain copy print?import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.util.; import org.springframework.util.PropertiesPersister; /** * Properties Util函数. * * @author uniz */ public class PropertiesUtils { private static final String DEFAULT_ENCODING = "UTF-8"; private static Logger logger = LoggerFactory.getLogger(PropertiesUtils.class); private static PropertiesPersister propertiesPersister = new (); private static ResourceLoader resourceLoader = new DefaultResourceLoader(); /** * 载入多个properties文件, 相同的属性在最后载入的文件中的值将会覆盖之前的载入. * 文件路径使用Spring Resource格式, 文件编码使用UTF-8. * * @see org.springframework.beans.factory.config. */ public static Properties loadProperties(String。
resourcesPaths) throws IOException { Properties props = new Properties(); for (String location : resourcesPaths) { logger.debug("Loading properties file from:" + location); InputStream is = null; try { Resource resource = resourceLoader.getResource(location); is = resource.getInputStream(); propertiesPersister.load(props, new InputStreamReader(is, DEFAULT_ENCODING)); } catch (IOException ex) { logger.info("Could not load properties from classpath:" + location + ": " + ex.getMessage()); } finally { if (is != null) { is.close(); } } } return props; } public static String getDataVal(String key) { try { Properties properties = PropertiesUtils.loadProperties("/config/config.properties"); if (properties == null) return ""; return new String((properties.getProperty(key)) .getBytes("ISO8859_1"), "utf-8"); } catch (Exception e) { e.printStackTrace(); return null; } } } [html] view plain copy print?[html] view plain copy print?。
9.properties文件怎么写
InputStream in = 类名.class.getClassLoader().getResourceAsStream("propertes名字.properties");
Properties prop = new Properties();
prop.load(in)
oracleDb_Driver = prop.getProperty("oracleDb_Driver-properties里面的字段");
spring的配置文件怎么写
1.spring的配置文件怎么写
标准的Spring配置文件编写:.mysql.jdbc.Driver jdbc:mysql://localhost/ssh?characterEncoding=utf-8 root123com/ssh/pojo/User.hbm.xmltrue。
2.在spring的配置文件中配置Person,写出配置信息;
<bean id="address" class="。Address">
<property name="city" value="XXX" />
</bean>
<bean id="person" class="。Person">
<property name="name" value="YYY" /> --->;值注入
<property name="addr" ref="address" /> --->;对象注入(ref=bean的id)
<property name="phone"> --->;集合对象注入
<value>123123123</value>
<value>123123123</value>
<value>123123123</value>
</property>
。.
</bean>
3.如何自动创建spring配置文件
方法如下:
1、打开Myeclipse,找到新建的工程项目;
2、右键点击--Myeclipse--project facets--install spring facet,按图示找到那片小绿叶;
3、打开后会有弹窗,选择spring版本,根据下载的spring文件获得;
4、此步点击next,可以根据自己的习惯配置,但是applicationcontext.xml文件的名称尽量不要改
5、这里是选择项目用到的jar包,如果自己有jar包,知道需要导入的jar包,可以把此处的复选框中的对勾去掉,自己导入更加安全;
6、当完成上一步时,就发现web.xml内容多了些配置内容。
4.java使用泛型时spring ioc的配置文件怎么写
一般是这么用的,比如:
public class{
private List<Dept> depts;
..get() set()
}
配置:(部分) xml头和xmlns合xsi自己根据自己的版本加吧
<bean id="user" class="com.*.User">
<!-- java.util.List -->
<property name="depts">
<list>
<value>1</value>
<ref bean="Dept" />
<bean class="com.*.Dept">
<property name="id" value="1" />
<property name="name" value="development" />
<property name="location" value="beijing" />
</bean>
</list>
</property>
</bean>
User user = appCtx.getBean("user");//配置中的id
List<Dept> depts = user.getDepts();
spring配置文件怎么写
1.spring的配置文件怎么写
标准的Spring配置文件编写:.mysql.jdbc.Driver jdbc:mysql://localhost/ssh?characterEncoding=utf-8 root123com/ssh/pojo/User.hbm.xmltrue。
2.spring hibernate springMVC 配置文件怎么写
所谓整合 我的理解就是把他们放在一起用。
.然后 由Spring的对象工厂来管理他们..前台JSP页面 用Struts传值到Action 写法还是Struts那样..Struts调用后台数据处理的时候 一般都是Biz biz = new BIz(); 这样new的对象 现在交给了Spring管理 在Sring里配置action和biz的关系就好了。后面Hibernate的用法 还是那样 . 只是把hibernate的配置信息放到了Spring的配置文件里而已。
3.编写一个spring的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
".humpic.tools.port.db.TelnetDAO">
<property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>
</beans>
4.多个spring配置文件依赖注入要怎么写
主要有两种方式:
1、在一个配置文件中使用import标签导入其他配置文件,即
applicationContext.xml中部分代码如下:
2、在web.xml中配置Spring配置文件处导入多个配置文件,即可
a、导入多个配置文件
web.xml部分代码如下:
contextConfigLocation
applicationContext-core.xml,
applicationContext-dao.xml,
applicationContext-service.xml,
applicationContext-action.xml
b、使用*通配符导入多个配置文件
web.xml部分代码如下:
contextConfigLocation
applicationContext-*.xml
5.如何自动创建spring配置文件
方法如下:
1、打开Myeclipse,找到新建的工程项目;
2、右键点击--Myeclipse--project facets--install spring facet,按图示找到那片小绿叶;
3、打开后会有弹窗,选择spring版本,根据下载的spring文件获得;
4、此步点击next,可以根据自己的习惯配置,但是applicationcontext.xml文件的名称尽量不要改
5、这里是选择项目用到的jar包,如果自己有jar包,知道需要导入的jar包,可以把此处的复选框中的对勾去掉,自己导入更加安全;
6、当完成上一步时,就发现web.xml内容多了些配置内容。
java怎么写配置文件
1.java配置文件怎么写
假设有如下xml配置文件config.xml:<?xml version="1.0" encoding="utf-8" ?>
2.java配置文件怎么写
假设有如下xml配置文件config.xml:
kiyhosinkiang100
可以用以下代码访问:
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
public class XmlConfigDemo {
public static void main(String[] args) {
try {
XMLConfiguration config = new XMLConfiguration("config.xml");
System.out.println(config.getList("name"));
System.out.println(config.getInt("info.age"));
} catch (ConfigurationException e) {
e.printStackTrace();
}
}
}
3.怎样读取和写我自己写的一个java配置文件
import java.io.File;import org.dom4j.Document;import org.dom4j.Element;import org.dom4j.io.SAXReader;/** * @Title: JavaBeanCreater.java * @Package liaodong.xiaoxiao.dom4j.sxd.bean * @Description: TODO(根据xml配置文件,生成javabean) * @author 辽东小小 * @date 2012-3-1 上午09:13:25 * @version V1.0 */public class JavaBeanCreater{ public static void main(String[] args) { //xml的存放路径 String xmlPath = "D:\\test\\javabean.xml"; File xmlFile = new File(xmlPath); StringBuffer sBuffer = new StringBuffer("public class "); SAXReader sReader = new SAXReader(); Document document; try { //读取xml文件,返回document对象 document = sReader.read(xmlFile); //获取根元素 Element rootElement = document.getRootElement(); // String className = rootElement.elementText("classname"); sBuffer.append(className).append("\n"); sBuffer.append("{\n"); String nature = rootElement.elementText("nature"); String natures[] = nature.split(","); //构造成员变量 for (String n : natures) { sBuffer.append("private String ").append(n).append(";\n"); } //构造set/get方法 for (String n : natures) { String methodName = n.substring(0, 1).toUpperCase()+n.substring(1); //拼写set方法 sBuffer.append("public void set").append(methodName).append("( String ").append(n).append(" )\n{"); sBuffer.append("this.").append(n).append(" = ").append(n).append(";\n}\n"); //拼写get方法 sBuffer.append("public String get").append(methodName).append(" ( )\n{\n"); sBuffer.append("return ").append(n).append(";\n}\n"); } //language 方法跟上面的类似 省略。
//写文件的方法也省略了。
sBuffer.append("}"); System.out.println(sBuffer.toString()); //}catch(Exception e){ e.printStackTrace(); } }}用Dom4j解析的xml##############################################################运行结果为:public class animal{private String name;private String food;private String age;public void setName( String name ){this.name = name;}public String getName ( ){return name;}public void setFood( String food ){this.food = food;}public String getFood ( ){return food;}public void setAge( String age ){this.age = age;}public String getAge ( ){return age;}}。
4.怎样读取和写我自己写的一个java配置文件
import java.io.File;import org.dom4j.Document;import org.dom4j.Element;import org.dom4j.io.SAXReader;/** * @Title: JavaBeanCreater.java * @Package liaodong.xiaoxiao.dom4j.sxd.bean * @Description: TODO(根据xml配置文件,生成javabean) * @author 辽东小小 * @date 2012-3-1 上午09:13:25 * @version V1.0 */public class JavaBeanCreater{ public static void main(String[] args) { //xml的存放路径 String xmlPath = "D:\\test\\javabean.xml"; File xmlFile = new File(xmlPath); StringBuffer sBuffer = new StringBuffer("public class "); SAXReader sReader = new SAXReader(); Document document; try { //读取xml文件,返回document对象 document = sReader.read(xmlFile); //获取根元素 Element rootElement = document.getRootElement(); // String className = rootElement.elementText("classname"); sBuffer.append(className).append("\n"); sBuffer.append("{\n"); String nature = rootElement.elementText("nature"); String natures[] = nature.split(","); //构造成员变量 for (String n : natures) { sBuffer.append("private String ").append(n).append(";\n"); } //构造set/get方法 for (String n : natures) { String methodName = n.substring(0, 1).toUpperCase()+n.substring(1); //拼写set方法 sBuffer.append("public void set").append(methodName).append("( String ").append(n).append(" )\n{"); sBuffer.append("this.").append(n).append(" = ").append(n).append(";\n}\n"); //拼写get方法 sBuffer.append("public String get").append(methodName).append(" ( )\n{\n"); sBuffer.append("return ").append(n).append(";\n}\n"); } //language 方法跟上面的类似 省略。
//写文件的方法也省略了。
sBuffer.append("}"); System.out.println(sBuffer.toString()); //}catch(Exception e){ e.printStackTrace(); } }}用Dom4j解析的xml##############################################################运行结果为:public class animal{private String name;private String food;private String age;public void setName( String name ){this.name = name;}public String getName ( ){return name;}public void setFood( String food ){this.food = food;}public String getFood ( ){return food;}public void setAge( String age ){this.age = age;}public String getAge ( ){return age;}}。
5.java 怎么读取配置文件
一.读取xml配置文件
(一)新建一个java bean(HelloBean. java)
java代码
(二)构造一个配置文件(beanConfig.xml)
xml 代码
(三)读取xml文件
1.利用ClassPathXmlApplicationContext
java代码
2.利用FileSystemResource读取
java代码
二.读取properties配置文件
这里介绍两种技术:利用spring读取properties 文件和利用java.util.Properties读取
(一)利用spring读取properties 文件
我们还利用上面的HelloBean. java文件,构造如下beanConfig.properties文件:
properties 代码
helloBean.class=chb.demo.vo.HelloBean
helloBean.helloWorld=Hello!chb!
属性文件中的"helloBean"名称即是Bean的别名设定,.class用于指定类来源。
然后利用org.springframework.beans.factory.support.PropertiesBeanDefinitionReader来读取属性文件
java代码
(二)利用java.util.Properties读取属性文件
比如,我们构造一个ipConfig.properties来保存服务器ip地址和端口,如:
properties 代码
ip=192.168.0.1
port=8080
三.读取位于Jar包之外的properties配置文件
下面仅仅是列出读取文件的过程,剩下的解析成为properties的方法同上
1 FileInputStream reader = new FileInputStream("config.properties");
2 num = reader.read(byteStream);
3 ByteArrayInputStream inStream = new ByteArrayInputStream(byteStream, 0, num);
四.要读取的配置文件和类文件一起打包到一个Jar中
String currentJarPath = URLDecoder.decode(YourClassName.class.getProtectionDomain().getCodeSource().getLocation().getFile(), "UTF-8"); //获取当前Jar文件名,并对其解码,防止出现中文乱码
JarFile currentJar = new JarFile(currentJarPath);
JarEntry dbEntry = currentJar.getJarEntry("包名/配置文件");
InputStream in = currentJar.getInputStream(dbEntry);
//以上YourClassName是class全名,也就是包括包名
修改:
JarOutputStream out = new FileOutputStream(currentJarPath);
out.putNextEntry(dbEntry);
out.write(byte[] b, int off, int len); //写配置文件
。。
out.close();
6.Java中的properties配置文件怎么写,代码
public static void main(String[] args) {
Properties p = new Properties();
p.setProperty("id", "user1");
p.setProperty("password", "123456");
try{
PrintStream stm = new PrintStream(new File("e:\test.properties"));
p.list(stm);
} catch (IOException e) {
e.printStackTrace();
}
}
7.java怎么在包中创建配置文件
先看代码目录结构:
src/weather/
QueryWeather.java
weather.xml
程序里面可以直接读取到weather.xml文件,代码如下:
private static String getXmlContent()throws IOException {
FileReader f = new FileReader("src/weather/weather.xml");
BufferedReader fb = new BufferedReader(f);
StringBuffer sb = new StringBuffer("");
String s = "";
while((s = fb.readLine()) != null) {
sb = sb.append(s);}return sb.toString();}但是一旦把这个class文件和xml文件打成jar包再运行,对不起,报错,QueryWeather.class字节码根本找不到weather.xml
在看打成jar包的结构:META-INFMANIFEST.MFweatherQueryWeather.class
weather.xml
用下面的方法就可以找到weather.xml
private static String getXmlContent()throws IOException {
Reader f = new InputStreamReader(QueryWeather.class.getClass().getResourceAsStream("/weather/weather.xml"));
BufferedReader fb = new BufferedReader(f);
StringBuffer sb = new StringBuffer("");
String s = "";
ssh的配置文件怎么写
1.ssh配置文件怎么写
讲不清楚,给你我的SPRING模板,你复制到eclipse里好好看看<?xml version="1.0" encoding="UTF-8"?>
<!-- 定义hibernateTemplate -->
2.ssh配置文件怎么写
讲不清楚,给你我的SPRING模板,你复制到eclipse里好好看看<?xml version="1.0" encoding="UTF-8"?><beans xmlns=".mysql.jdbc.Driver</value> </property> <property name="url"> <value>jdbc:mysql://localhost/model</value> </property> <property name="username"> <value>root</value> </property> <property name="password"> <value>admin</value> </property> </bean> <;!-- 定义SessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </prop> <prop key="hibernate.show_sql">false</prop> </props> </property> <property name="mappingResources"> <list> <value>com/javaweb/po/User.hbm.xml</value> </list> </property> </bean> <;!-- 定义hibernateTemplate --> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory"> <ref bean="sessionFactory"/> </property> </bean> <;!-- 配置DAO组件 --> <bean id="userDAO" class="com.javaweb.dao.UserDAOImpl"> <property name="hibernateTemplate"> <ref bean="hibernateTemplate"/> </property> </bean> <;!-- 配置业务逻辑组件 --> <bean id="userService" class="com.javaweb.service.UserServiceImpl"> <;!-- 为业务逻辑组件注入DAO组件 --> <property name="userDAO" ref="userDAO"></property> </bean> <;!-- 创建Action实例 --> <bean id="loginAction" class="com.javaweb.action.LoginAction" scope="prototype"> <property name="userService" ref="userService"></property> </bean></beans>。
3.java程序员面试时,ssh框架的配置文件怎么口语描述
1.ssh需要使用到哪些配置文件?
使用spring配置jdbc
struts配置文件、spring配置文件、hibernate映射文件
2.每个配置文件分别需要配置一些什么东西?
①struts.xml中主要是对action的配置(控制界面与后台交互)、拦截器配置,
②spring配置中,包含依赖注入、数据库连接池配置、事务声明、日志配置等。
③映射文件中主要写的是实体类与数据库的关系(如果你熟悉一对多、多对多这种配置和机制的话,也可以简单说一下)
(捡你熟悉的说,因为面试官会从你这次的回答中,延伸出下面的问题)
3.ssh的配置运行的流程是怎样的?可以用登录来举例说明
登陆请求 → struts2加载类(FilterDispatcher) → 读取配置文件中对应action
→ 派发请求 →调用action→启用拦截器 → 执行action调用的方法(如默认execute) → 通过业务类对象调用业务方法(spring中配置的bean在项目启动时已经加载) → 业务方法调用dao方法(获取数据),进行业务处理(一般声明事务会监控在业务层) → 返回处理结果到action → action返回响应 → FilterDispatcher根据配置查找响应的是什么信息如:SUCCESS、ERROR,将跳转到哪个jsp页面 → 页面展示结果
注1:struts2.1.6(具体版本记不清了,你可以查下)以后版本加载类替换成了(StrutsPrepareAndExecuteFilter)
注2:面试的时候,说道ssh的话,建议你去具体熟悉一种技术的基本机制。
面试时你可以说熟练使用ssh框架(一般这时面试官会问你,对哪个比较熟悉) → 底层机制的话,对XXX比较熟悉(简单介绍一下你认知中的XXX)→ 这时候根据你的准备去说!~
有问题再追问,good luck!~
4.ssh eclipse 如何写配置文件
1,有可能配置文件没有声明编码格式。
即:hibernate.cfg.xml文件需要添加以下代码。<hibernate-configuration> <session-factory> <property name="connection.username">root</property> <property name="connection.password"></property> <property name="connection.url"> jdbc:mysql://127.0.0.1/test </property> <property name="connection.characterEncoding">utf8</property> <property name="connection.useUnicode">true</property> <property name="dialect"> org.hibernate.dialect.MySQLDialect </property> <property name="myeclipse.connection.profile">mysql</property> <property name="connection.driver_class"> com.mysql.jdbc.Driver </property> <mapping…… /></session-factory></hibernate-configuration>2,有可能在页面跳转时就出现乱码,即写入数据库前就出现乱码。
这样需要配置过滤器。 在web.xml文件中添加如下代码。
<filter> <filter-name>CheckCodeServlet</filter-name> <filter-class> com.CheckCodeServlet </filter-class> </filter> <filter-mapping> <filter-name>CheckCodeServlet</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>; 然后在com包下创建CheckCodeServlet类。代码如下。
package com;import java.io.IOException;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet..mysql.jdbc.Driver
这样需要配置过滤器。 在web.xml文件中添加如下代码。
package com;import java.io.IOException;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;public class CheckCodeServlet extends HttpServlet implements Filter{ public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { // TODO Auto-generated method stub request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); filterChain.doFilter(request, response); } public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub }}这个是过滤器。3,有可能是数据库编码格式与写入数据的编码格式不一致。
建议最好用统一的编码格式。
转载请注明出处育才学习网 » springmvc的配置文件怎么写
育才学习网