NutzCN Logo
问答 如何载入resources外面的资源文件?
发布于 3231天前 作者 wukonggg 2451 次浏览 复制 上一个帖子 下一个帖子
标签:

maven构建的命令行工程,在和src并列的etc目录中放置配置文件。具体类如下。请问应该如何配置? 谢谢~

public class IocMaster {
	
	private static final Log log = Logs.get();
	
	private static Ioc ioc = null;
	
	private IocMaster() {
		throw new RuntimeException("Shit! What are you doing?!");
	}


	public static Ioc getInstance() {
		if (null != ioc) {
			return ioc;
		}
		
        try {
            ioc = new NutIoc((new ComboIocLoader(
                "*js", "./etc/"
                , "*anno", "com.nari.nwims.skengine"
//                , "*tx"
                )));
        } catch (ClassNotFoundException e) {
            String msg = "create ioc failed...";
            log.error(msg);
            log.error(e.getMessage());
            throw new RuntimeException(e);
        }
        return ioc;
	}

}

32 回复

放在resources之外,编译的时候根本不找, 除非改了pom.xml里面资源的路径

@Rekoe 好像不行

单元测试:

public class IocMasterTest {

    @Test
    public void readProperties(){
        PropertiesProxy proxy = IocMaster.getInstance().get(PropertiesProxy.class);
        Assert.assertTrue(null != proxy.get("db.driver"));
    }



}

报错:

ALL Nutz Log via Log4jLogAdapter
Log4j: 14:57:13 INFO     org.nutz.log.Logs [<clinit>] - Nutz is licensed under the Apache License, Version 2.0 .
Report bugs : https://github.com/nutzam/nutz/issues
Log4j: 14:57:13 INFO  org.nutz.resource.impl.ErrorResourceLocation [<init>] - ErrorResourceLocation [loc=D:\Document\Work\Hoperun\Main\PRJ-2015-%e5%8d%97%e7%bd%91IMS\SVN-XA\CODE\06-statkpi-engine\nwims-statkpi-engine\target\classes], maybe it is in your classpath, but not exist
Log4j: 14:57:14 DEBUG org.nutz.resource.Scans [<init>] - Locations for Scans:
[JarResourceLocation [jarPath=D:\Lab\bin\Java\jdk1.6.0_45\jre\lib\ext\sunjce_provider.jar], JarResourceLocation [jarPath=D:\Lab\bin\Java\jdk1.6.0_45\jre\lib\jce.jar], FileSystemResourceLocation [root=D:\Document\Work\Hoperun\Main\PRJ-2015-南网IMS\SVN-XA\CODE\06-statkpi-engine\nwims-statkpi-engine], JarResourceLocation [jarPath=D:\Lab\bin\Java\jdk1.6.0_45\jre\lib\management-agent.jar], JarResourceLocation [jarPath=D:\Lab\bin\maven\.m2\repository\junit\junit\4.11\junit-4.11.jar], JarResourceLocation [jarPath=D:\Lab\bin\maven\.m2\repository\com\alibaba\druid\1.0.14\druid-1.0.14.jar], JarResourceLocation [jarPath=D:\Lab\bin\Java\jdk1.6.0_45\jre\lib\resources.jar], JarResourceLocation [jarPath=D:\Lab\bin\maven\.m2\repository\log4j\log4j\1.2.17\log4j-1.2.17.jar], JarResourceLocation [jarPath=D:\Lab\bin\maven\.m2\repository\com\oracle\ojdbc6\11.2.0.4.0\ojdbc6-11.2.0.4.0.jar], JarResourceLocation [jarPath=D:\Lab\bin\Java\jdk1.6.0_45\jre\lib\deploy.jar], JarResourceLocation [jarPath=D:\Lab\bin\maven\.m2\repository\org\nutz\nutz\1.b.53\nutz-1.b.53.jar], JarResourceLocation [jarPath=D:\Lab\bin\Java\jdk1.6.0_45\jre\lib\javaws.jar], JarResourceLocation [jarPath=D:\Lab\bin\Java\jdk1.6.0_45\jre\lib\ext\sunmscapi.jar], JarResourceLocation [jarPath=D:\Lab\bin\Java\jdk1.6.0_45\jre\lib\ext\localedata.jar], JarResourceLocation [jarPath=D:\Lab\bin\Java\jdk1.6.0_45\jre\lib\rt.jar], JarResourceLocation [jarPath=D:\Lab\bin\Java\jdk1.6.0_45\jre\lib\ext\dnsns.jar], FileSystemResourceLocation [root=D:\Document\Work\Hoperun\Main\PRJ-2015-南网IMS\SVN-XA\CODE\06-statkpi-engine\nwims-statkpi-engine\target\test-classes], JarResourceLocation [jarPath=D:\Lab\bin\IntelliJ IDEA 14.1.4\plugins\junit\lib\junit-rt.jar], JarResourceLocation [jarPath=D:\Lab\bin\IntelliJ IDEA 14.1.4\lib\idea_rt.jar], JarResourceLocation [jarPath=D:\Lab\bin\Java\jdk1.6.0_45\jre\lib\plugin.jar], FileSystemResourceLocation [root=D:\Document\Work\Hoperun\Main\PRJ-2015-南网IMS\SVN-XA\CODE\06-statkpi-engine\nwims-statkpi-engine\target\classes], JarResourceLocation [jarPath=D:\Lab\bin\Java\jdk1.6.0_45\jre\lib\jsse.jar], JarResourceLocation [jarPath=D:\Lab\bin\Java\jdk1.6.0_45\lib\tools.jar], JarResourceLocation [jarPath=D:\Lab\bin\Java\jdk1.6.0_45\lib\jconsole.jar], JarResourceLocation [jarPath=D:\Lab\bin\Java\jdk1.6.0_45\jre\lib\charsets.jar], ErrorResourceLocation [loc=D:\Document\Work\Hoperun\Main\PRJ-2015-%e5%8d%97%e7%bd%91IMS\SVN-XA\CODE\06-statkpi-engine\nwims-statkpi-engine\target\classes], JarResourceLocation [jarPath=D:\Lab\bin\maven\.m2\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar]]
Log4j: 14:57:14 DEBUG org.nutz.resource.Scans [scan] - Found 2 resource by src( etc/ ) , regex( ^(.+[.])(js|json)$ )
Log4j: 14:57:14 DEBUG org.nutz.resource.Scans [scan] - Found 1 resource by src( /etc/ ) , regex( ^(.+[.])(js|json)$ )
Log4j: 14:57:14 DEBUG org.nutz.ioc.loader.json.JsonLoader [<init>] - loading ioc js config from [db.js]
Log4j: 14:57:14 DEBUG org.nutz.ioc.loader.json.JsonLoader [<init>] - Loaded 3 bean define from path=[/etc/] --> [dataSource, dao, config]
Log4j: 14:57:14 DEBUG org.nutz.resource.Scans [scan] - Found 5 resource by src( com/nari/nwims/skengine/ ) , regex( ^.+[.]class$ )
Log4j: 14:57:14 DEBUG org.nutz.ioc.loader.annotation.AnnotationIocLoader [addClass] - Found a Class with Ioc-Annotation : class com.nari.nwims.skengine.glance.LittleBlueBird
Log4j: 14:57:14 DEBUG org.nutz.castor.Castors [reload] - Using 91 castor for Castors
Log4j: 14:57:14 INFO  org.nutz.ioc.loader.annotation.AnnotationIocLoader [<init>] - Scan complete ! Found 1 classes in 1 base-packages!
beans = ["littleBlueBird"]
Log4j: 14:57:14 INFO  org.nutz.ioc.impl.NutIoc [<init>] - NutIoc init begin ...
Log4j: 14:57:14 INFO  org.nutz.ioc.impl.NutIoc [<init>] - ... NutIoc init complete
Log4j: 14:57:14 DEBUG org.nutz.ioc.impl.NutIoc [get] - Get 'propertiesProxy'<class org.nutz.ioc.impl.PropertiesProxy>
Log4j: 14:57:14 DEBUG org.nutz.ioc.impl.NutIoc [get] - 	 >> Load definition

org.nutz.ioc.IocException: Object 'propertiesProxy' without define! For object [propertiesProxy] - type:[class org.nutz.ioc.impl.PropertiesProxy]
	at org.nutz.ioc.impl.NutIoc.get(NutIoc.java:203)
	at org.nutz.ioc.impl.NutIoc.get(NutIoc.java:221)
	at org.nutz.ioc.impl.NutIoc.get(NutIoc.java:140)
	at com.nari.nwims.skengine.IocMasterTest.readProperties(IocMasterTest.java:16)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78)
	at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)
	at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Caused by: org.nutz.ioc.ObjectLoadException: Object 'propertiesProxy' without define!
	at org.nutz.ioc.loader.combo.ComboIocLoader.load(ComboIocLoader.java:149)
	at org.nutz.ioc.impl.NutIoc.get(NutIoc.java:168)
	... 29 more


Process finished with exit code -1

应该去改pom.xml, 把etc目录也列入resources

@wendal 之所以在外面用etc而不是直接resources是因为部署的时候这部分会改,并不是打包在jar里边的

你可以打包的时候 把不用的资源过滤掉

我是只 把需要打的打进去

<resource>
				<directory>src/main/resources</directory>
				<includes>
					<include>com/rekoe/web/freemarker/*.*</include>
				</includes>
			</resource>

@wukonggg 在Scans类添加自定义路径

Scans.me().registerLocation(new File(xxxx).toURI().toURL());

@Rekoe 是可以过滤。但是过滤了以后,我运行时到哪里去找配置文件呢?

@wendal 这条语句具体添加在什么位置?感觉new出ioc之前?

@wukonggg y,当然是之前

环境感知类似的一个实现,我这里貌似有这个的代码,开发的时候我随便玩儿从 classpath(resource 目录)加载,上线之后从线上机器的绝对路径去读取,避免数据库地址啊密码啊什么的泄露

@wukonggg
我自定义了一个resourceLoader
去项目的 ../conf/下找文件

这是我想要的结构。etc中是部分配置值。

QQ截图20160217151723_png

public class PropertiesLoader extends MapLoader {

	private static final String SYSTEM_PROPERTIES = "system.properties";

	public PropertiesLoader() {
		NutMap map = new NutMap();
		/** 优先找测试环境下的 */
		File file = Files.findFile(SYSTEM_PROPERTIES + "_dev");
		if (Lang.isEmpty(file)) {
			file = Files.findFile(SYSTEM_PROPERTIES);
		}
		if (Lang.isEmpty(file)) {
			String lastPath = Mvcs.getNutConfig().getAppRoot() + "/../conf/" + SYSTEM_PROPERTIES;
			file = Files.findFile(lastPath);
		}
		if (Lang.isEmpty(file)) {
			throw Lang.makeThrow("Can Not Find Resource [%s] Any More", SYSTEM_PROPERTIES);
		}
		map.setv("type", "org.nutz.ioc.impl.PropertiesProxy");
		ArrayList<String> args = new ArrayList<String>();
		args.add(file.getPath());
		map.setv("args", args);
		getMap().put("conf", map);
	}
}

路径结构

-s1
--- conf
---war

@Rekoe 貌似接近了。这个Loader怎么用呢? 是在new ioc的时候?

//这样?
ioc = new NutIoc((new PropertiesLoader());

貌似这样就只能读取配置文件了,原有的注解方式,还有事务控制,怎么延续用呢?

ComboIocLoader

@wukonggg
加载
MainModule 中

@IocBy(type = ComboIocProvider.class, args = { "*js", "ioc/", "*xxxx.com.PropertiesLoader"})

@wendal 还是没有搞好。。有没有使用nutz的ioc的命令行程序的例子?我想看看参考一下

@wukonggg 到底是不会组合多个ioc loader还是不知道scans用法

@wendal 组合ioc loader的问题。在web程序中我知道怎么组合,但命令行程序现在有问题。

场景就是db.js还是在src/main/resources中。但是db.properties需要放到src外面。
开发时,可以在和src在同级目录。
部署时,可以和jar同级目录
大概就是这个意思。

@wukonggg new NutIoc(new ComboIocLoader(........))

而且combo有add方法

@Rekoe

你的方法
1、写一个PropertiesLoader
2、配置这样写
@IocBy(type = ComboIocProvider.class, args = { "*js", "ioc/", "*xxxx.com.PropertiesLoader"})
3、那你的js里边是什么写法?放在什么位置?

@Rekoe js的ioc文件里边怎么引用那个properties

@wukonggg 别管那个 那个是加载jar包中的

来自 iPhone 6

@wukonggg
和正常一样引用

来自 iPhone 6

@Rekoe 正常引用指的是。。。 这样肯定还是不对的哥。。我的代码如下:
prjxxx/src/main/resources/db.js

config : {
        type : "org.nutz.ioc.impl.PropertiesProxy",
        fields : {
            paths : ["db.properties"]
        }
    },
    dataSource: {
        type: "com.alibaba.druid.pool.DruidDataSource",
        events: {
            depose: 'close'
        },
        fields: {
            driverClassName      : {java : "$config.get('db.driver')"},
            url                  : {java : "$config.get('db.url')"},
            username             : {java : "$config.get('db.username')"},
            password             : {java : "$config.get('db.password')"},
            testWhileIdle        : {java : "$config.get('db.testWhileIdle')"},
            validationQuery      : {java : "$config.get('db.validationQuery')"},
            maxActive            : {java : "$config.get('db.maxActive')"}
        }
    },

我的ioc loader

ioc = new NutIoc(new ComboIocLoader(
                "*xxx.skengine.nutz.DbPropsLoader"
                , "*js", "."
                , "*anno", "xxx.skengine"
                , "*tx"
                ));

prjxxx/etc/db.properties

db.driverClassName=oracle.jdbc.driver.OracleDriver

我的loader

public class DbPropsLoader extends MapLoader {

    private static final String DB_PROPS_PROD = "db.properties";

    public DbPropsLoader() {
        NutMap map = new NutMap();

        String lastPath = System.getProperty("user.dir") + "/etc/" + DB_PROPS_PROD;
        File file = Files.findFile(lastPath);

        if (Lang.isEmpty(file)) {
            throw Lang.makeThrow("Can Not Find Resource [%s] Any More", DB_PROPS_PROD);
        }
        map.setv("type", "org.nutz.ioc.impl.PropertiesProxy");
        ArrayList<String> args = new ArrayList<String>();
        args.add(file.getPath());
        map.setv("args", args);
        getMap().put("conf", map);
    }
}

@Rekoe 如我上面28楼的代码,ioc load以后,是找不到db.properties的。因为根据js,他还是会找名字叫config的类,然后根据paths来找。这和自定义的loader怎么关联起来?

@wukonggg
你的自定义loader中的变量是conf

来自 iPhone 6

@Rekoe OK了!太感动了,感谢人民感谢党,感谢Rekoe Wendal!

根据28楼,再调整js到如下就ok了

var ioc = {
    dataSource: {
        type: "com.alibaba.druid.pool.DruidDataSource",
        events: {
            depose: 'close'
        },
        fields: {
            driverClassName      : {java : "$conf.get('db.driver')"},
            url                  : {java : "$conf.get('db.url')"},
            username             : {java : "$conf.get('db.username')"},
            password             : {java : "$conf.get('db.password')"},
            testWhileIdle        : {java : "$conf.get('db.testWhileIdle')"},
            validationQuery      : {java : "$conf.get('db.validationQuery')"},
            maxActive            : {java : "$conf.get('db.maxActive')"}
        }
    },
    dao: {
        type: "org.nutz.dao.impl.NutDao",
        args: [
            {refer: "dataSource"}
        ]
    }
};

这个贴可以关闭了~

添加回复
请先登陆
回到顶部